Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all 27407 articles
Browse latest View live

VS 2013 Click Webbrowser button no ID, possibly javascript

$
0
0
I am working on a personal project that will help my speed things up. I'm fairly good at figuring out how to click buttons with an id where you getelementby id and then invokemember("click"); but this one I am trying to click is somewhat over my head. I have done lots of research and multiple attempts but still have no luck. By the way, the webpage changes some when the button (image) is clicked; it does not redirect the webbrowser anywhere. Here is the source of the element and I think it involves some javascript which I have no experience with.

HTML Code:

<div class="enterFlavor">       
        <p class="mediumText">This drink?</p>       
        <a href="javascript:;" brand-id="BC9">
                <img src="http://************.com/bevprod/BC9.png" alt="Seagrams Cherry" height="140" width="90">
        </a>
</div>

Here is one attempt I tried. I have attempted getting the element by point but that does not seem very efficient since the form is not in the same position every time.

Code:

Dim AllElements As HtmlElementCollection = WebBrowser1.document.All
        For Each indelem As HtmlElement In AllElements
            If indelem.GetAttribute("className") = "enterFlavor" Then
                Dim xpos As Integer = GetXOffSet(indelem)
                Dim finalx As Double = xpos * 0.5
                Dim ypos As Integer = GetYOffSet(indelem)
                Dim finaly As Double = ypos * 0.5
                Dim NewPoint As New Point(finalx, finaly)
                Dim area As HtmlElement = WebBrowser1.document.GetElementFromPoint(NewPoint)
                area.InvokeMember("click")
            End If
        Next

Other attempt

Code:

Dim allelements As HtmlElementCollection = WebBrowser1.document.All
        For Each webpageelement As HtmlElement In allelements
            If webpageelement.GetAttribute("className") = "enterFlavor" Then
                If webpageelement.InnerText = "Seagrams Cherry" Then
                    webpageelement.InvokeMember("click")
                End If             
               
            End If
        Next

It's just a button I wanna click but it is really frustrating me cause it seems so simple. Any help would be much appreciated

VS 2008 newbie having problem with first calculator

$
0
0
hi dear all, I am a newbie with VB.net. would like to ask why my calculator project can only add, multiply and divide to get proper answers? when I subtract 63 from 7, I get a positive 56 instead of -56. I want the label to show -56 instead of 56. what am I missing? please help. thank you.

VS 2015 Finding a clever way to store more digits.

$
0
0
It seems like the type "Double" can store the most numerical digits.

"Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers that range in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. "

I am making large exponential calculations and once I reach this max bound, the answer becomes ∞.

I was thinking of making an double array that stores values larger but I'm not too sure how to do this.

total = (36) ^ cLength

where cLength can be 1 to 2.147bil

I reach the bound when cLength = 198

1.40570811483169E+308

But I want to store many values! More than E+308 and represent them in digits.

Printing to default printer rather than selected printer

$
0
0
Good Morning All,

I am trying to print a PDF document off from within my application. Previously i have been using the following code:

Code:

Dim PrintPDF As New ProcessStartInfo
    PrintPDF.UseShellExecute = True
    PrintPDF.Verb = "print"
    PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
    PrintPDF.FileName = dirName & fileName 'fileName is a string parameter
    Process.Start(PrintPDF)

This code is working however it doesn't let the user select the printer they want to print the document to it only prints to the selected printer. This used to be ok however we have had an issue recently where the default printer was unavailable and as such the user couldn't print the document without changing their default printer on windows.

After doing some research i have the following code which i have debugged from an on-line example i have found.

Code:

'Declare a printerSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing


Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click

    Try

        dim fileName As String = "C:\534679.pdf"


        'Get de the default printer in the system
        defaultPrinterSetting = DocumentPrinter.GetDefaultPrinterSetting


        'uncomment if you want to change the default printer before print
        'DocumentPrinter.ChangePrinterSettings(defaultPrinterSetting)


        'print your file
        If PrintFile(fileName, defaultPrinterSetting) then
            msgbox ("your print file success message")
        else
            msgbox ("your print file failed message")

        end if

    Catch ex As Exception
        mssbox(ex.Message.toString)
    End Try

End Sub


Public NotInheritable Class DocumentPrinter

    Shared Sub New()

    End Sub

    Public Shared Function PrintFile(ByVal fileName As String, printerSetting As System.Drawing.Printing.PrinterSettings) As Boolean

        Dim printProcess As System.Diagnostics.Process = Nothing
        Dim printed As Boolean = False

        Try

            If PrinterSetting IsNot Nothing Then


                Dim startInfo As New ProcessStartInfo()

                startInfo.Verb = "Print"
                MsgBox(printerSetting.PrinterName)
                startInfo.Arguments = printerSetting.PrinterName    ' <----printer to use----
                startInfo.FileName = fileName
                startInfo.UseShellExecute = True
                startInfo.CreateNoWindow = True
                startInfo.WindowStyle = ProcessWindowStyle.Hidden

                Using print As System.Diagnostics.Process = Process.Start(startInfo)

                  'Close the application after X milliseconds with WaitForExit(X) 

                    print.WaitForExit(10000)

                    If print.HasExited = False Then

                        If print.CloseMainWindow() Then
                            printed = True
                        Else
                            printed = True
                        End If

                    Else
                        printed = True

                    End If

                    print.Close()

                End Using


        Else
            Throw New Exception("Printers not found in the system...")
        End If


        Catch ex As Exception
            Throw
        End Try

        Return printed

    End Function


    ''' <summary>
    ''' Change the default printer using a print dialog Box
    ''' </summary>
    ''' <param name="defaultPrinterSetting"></param>
    ''' <remarks></remarks>
    Public Shared Sub ChangePrinterSettings(ByRef defaultPrinterSetting As System.Drawing.Printing.PrinterSettings)

        Dim printDialogBox As New PrintDialog

        If printDialogBox.ShowDialog = Windows.Forms.DialogResult.OK Then

            If printDialogBox.PrinterSettings.IsValid Then
                defaultPrinterSetting = printDialogBox.PrinterSettings
            End If

        End If

    End Sub



    ''' <summary>
    ''' Get the default printer settings in the system
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetDefaultPrinterSetting() As System.Drawing.Printing.PrinterSettings

        Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing

        For Each printer As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters


            defaultPrinterSetting = New System.Drawing.Printing.PrinterSettings
            defaultPrinterSetting.PrinterName = printer

            If defaultPrinterSetting.IsDefaultPrinter Then
                Return defaultPrinterSetting
            End If

        Next

        Return defaultPrinterSetting

    End Function

End Class

This is working fine and allowing me to select the printer to print to and the message box is displaying the selected printer however the document prints to the default printer still rather than the user selected printer. Can someone please help me out with what's going on.

Thanks in advanced

Frosty

VS 2015 VB Code Windows, Placement of new subs.

$
0
0
Is there an option anywhere that changes the placement of new subs going into code?

Say I have a KeyDown event sub in my code, neatly located in a relevant #Region, but I also want a KeyPress. I make sure my cursor is in the KeyDown event and select KeyPress from the drop down at the top left.

I get the new event sub placed right at the end of my code, I then have to cut and paste it to the location I want it. This gets extremely boring when you're working with long code lists.

Thanks.

VS 2015 KeyPress / KeyDown event in DataGridView

$
0
0
Hi folks.

The KeyPress and KeyDown events fire fine when using keys to navigate a grid, but they don't fire when editing data in a cell, I can't see a CellKeyDown event.

Could someone please tell me where I should be capturing the user input?

Thanks.

VS 2015 If Else End If - Evaluation.

$
0
0
Has the evaluation of the the If structure changed?

Code:

  If Trim(txtSearch.Text) = "" Then
            SearchLength = 0
        Else
            SearchLength = CInt(txtSearch.Text)
        End If

throws an error on the else structure even if the first evaluation is true. I'm sure this didn't used to be the case?

I know in the past if this had been built on one line it would have failed, but not with the above structure.

So now I have to build 2 If statements, surely that's part of the point of Else?

VS 2010 Run a batch file from a VB console application and get the output

$
0
0
Can some one explain to me how to run a batch file from a console application and get the output. I can do this from a Windows app but this is the first time I have had to do it from a console application. The code below runs the batch fine but when I try to capture the output as in example 2 I get a "system can not find file specified" error.

Code:

      Dim p As Process = Nothing
        Try

            Dim targetDir As String
            targetDir = String.Format("\\O2NCOALINK\MoverMatch\")

            p = New Process()
            With p.StartInfo
                .FileName = "NCLBuild.BAT"
                .CreateNoWindow = True
                .WorkingDirectory = targetDir
                .Arguments = String.Format("VB.NET Console application")
            End With

            p.Start()
            p.WaitForExit()

        Catch ex As Exception

            Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString())

        End Try

Code:

      Dim p As Process = Nothing

        Try

            Dim targetDir As String
            targetDir = String.Format("\\O2NCOALINK\MoverMatch\")

            p = New Process()
            With p.StartInfo
                .FileName = "NCLBuild.BAT"
                .CreateNoWindow = True
                .WorkingDirectory = targetDir
                .UseShellExecute = False
                .RedirectStandardOutput = True
                .RedirectStandardError = True
                .Arguments = String.Format("VB.NET Console application")
            End With

            p.Start()

        Catch ex As Exception

            Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString())

        End Try
        Dim std_out As String = p.StandardOutput.ReadToEnd
        Dim std_err As String = p.StandardError.ReadToEnd


VS 2013 Delete Border in Windows Form

$
0
0
Hey Community,

I am new at coding :( and have a question. I wanna delete the white borders in my Form which you can see in the Screenshot (I marked it red). I don't know how to do that.
Name:  Screenshot_3.jpg
Views: 66
Size:  61.7 KB

I hope you could help me ;)
Attached Images
  

VS 2013 Change ReturnAddress for 3Ttemplates

$
0
0
Hello,
I have my main ReturnAddress set up in Word 2013 Options.
I have two other Letter Templates that I would like to change the ReturnAddress on the Envelope.
I have been trying to do this with VB Document.Open, I immediately go to an envelope with the correct ReturnAddress but it replaces the Template...Start again... Been going around in circles.
Thanks,
Raney

VS 2015 How to receive serial data in byte array then display to the richtextbox??

$
0
0
Hi guys :wave:

I'm working on a modbus project right now. it's a real time monitoring UI for some sensors.
But I have some problems here.
1. How do I receive a frame of 73 byte data array in a row and then display it to richtextbox?

here's my code that can work so far
Code:

Private Sub serialport1_datareceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        If (SerialPort1.IsOpen) Then

            Do While SerialPort1.BytesToRead > 0

                Try

                    sData = SerialPort1.ReadByte()

                    Me.Invoke(New EventHandler(AddressOf doupdate))

                Catch

                End Try

            Loop
        End If
    End Sub

    Public Sub doupdate(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim i As Integer = sData
        Dim s As String = ""

        s = i.ToString("x2")

        TextBox1.Text = TextBox1.Text & (s.ToUpper) & " "
        RichTextBox2.Text = RichTextBox2.Text & (s.ToUpper) & " "
     

    End Sub

bu it is very complicated to parsed the data from textbox, I've successfully parse the data and get the real meter value. but that's when I used 2 buttons to send and parse data. when I tried switch it using timer it's error. So my idea is try to get the serial data in byte array then display it to textbox and parse it simultaneously. because I plan to use this program up to 30 slave/sensor connected. So I need to parse it very quickly to get the real time data for each sensor/slave. Anybody help??

VS 2015 Protecting an Enum in a Class inheriting an object

$
0
0
Hi folks. This problem probably has a really simple answer and will expose my lack of basic class knowledge, but here we go, I'm ready for a slap around the head!

I have a class that uses a text box to limit character input. About as simple a class as you could imagine. It has an Enum which has an associated property and local variable which look after the type of input needed, Alpha, Numeric, Currency etc.

It all works wonderfully but there is a niggle.

The Enum is exposed and I can't find how to hide it. I can't make the Enum private as apparently the property then can't use 'value'. ?

I'm a bit confused as I thought the idea of using properties was to hide the local variables.


Code:

Inherits TextBox
    Private iType As InpType = InpType.NotSet

  Enum InpType
        Numeric
        Alpha
        AlphaNumeric
        NotSet
    End Enum

  Public Property InputType As InpType
        Get
            Return iType
        End Get
        Set(value As InpType)
            iType = value
        End Set
    End Property

Disable Auto scroll of text in Richtextbox

$
0
0
Hi experts,


How can i prevent the text from scrolling down when the text/string is out of bounds on the bottom of the richtextbox.

Can anyone help me.

Please.


Thanks and Best Regards.

Best way to bind complexly related data to DataGridView

$
0
0
Hi folks

Im trying to figure out the best way of going about binding some data to a DataGridView. I can bind simple collections etc no problem but now i have to collections with relationships between them that affect what should be shown in the grid.

To explain from the start I have data represented in collections of different types of objects, Mappings and Command, populated by deserializing objects from JSON.

vb.net Code:
  1. Public Class Mapping
  2.     Public Property Description as String
  3.     Public Property MaximumCommand As byte
  4.     Public Property DefaultCommand As byte
  5.     Public Property MinimumCommand As byte
  6.     '...
  7. End Class
  8.  
  9. Public class Command
  10.     Public Property Code As Byte
  11.     Public Property Value As Decimal
  12.     '...
  13. End Class
  14.  
  15. Dim Mappings as BindingList(Of Mapping)
  16. Dim Commands as BindingList(Of Command)

The DataGridView has four columns "Description" (a DataGridViewComboBoxColumn), "Upper Value", "Default Value" and "Lower Value".

I can bind the DGV ComboBoxColumn to the Mappings such the the options in the drop-down are the description strings, but after that it gets complicated.

I'd like for the selected item on the Description column to be set by the Commands, where Command.Code is equal to Mapping.DefaultCommand

And also for the value columns to be equal to the Command.Value where the Command.Code is equal to the Mapping.*Command of the Mapping selected by the previous condition.


For an example:

vb.net Code:
  1. Dim MyMapping As Mapping = New mapping
  2. Dim Command1 As Command = New Command
  3. Dim Command2 As Command = New Command
  4. Dim Command3 As Command = New Command
  5.  
  6. Mapping.Description = "foobar"
  7. Mapping.MaximumCommand = 50
  8. Mapping.DefaultCommand = 63
  9. Mapping.MinimumCommand = 70
  10.  
  11. Command1.Code = 50
  12. Command1.Value = 100
  13.  
  14. Command2.Code = 63
  15. Command2.Value = 50
  16.  
  17. Command3.Code = 70
  18. Command3.Value = 0

The DGV should then show

Code:

Description | Upper Value | Default Value | Lower Value |
-------------+-------------+---------------+-------------+
 foobar      | 100        | 50            | 0          |


I also have to be able to do the reverse with data edited or added in the DGV by the user :eek: such that changes affect the Commands (the Mappings are fixed). If I have to do that by reading each cell of the table and repopulating the lists it kind of takes away the usefulness of the binding :\

I was thinking maybe of making a new List() from a set of LINQ queries and binding to that but Im not entirely sure how to best do that?
Or even if there might be another better method?

Thanks!

VS 2012 How to bring an item to the top

$
0
0
Name:  mt0ime.jpg
Views: 56
Size:  46.4 KB
I'd like to select one of the controls in IDE and bring it to the top even if its hidden behind another control . In vb6 I could do that with CTRL+J. Does anyone knows if there's a way to do that?
Attached Images
 

VS 2010 Change DefaultConnectionSettings for Proxy and Autoconfiguration

$
0
0
Hi all,

I am attempting to run a script to disable and enable the two LAN settings. I found two scripts online.

for VBS:
Code:

const HKEY_CURRENT_USER = &H80000001
 strComputer = "."

 Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
 strComputer & "\root\default:StdRegProv")

 'Define byte's array
 Dim bArray

 strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"

 'Fill array with values of the key;
 'array elemnts starts from 0 an up,
 'so I need to change bArray(2) element's value

 objReg.GetBinaryValue HKEY_CURRENT_USER, strKeyPath, "DefaultConnectionSettings", bArray

 'Changing value
 bArray(8) = 7

 'Write infromation back
 objReg.SetBinaryValue HKEY_CURRENT_USER, strKeyPath, "DefaultConnectionSettings", bArray

 Set objReg = Nothing

Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe https://x.com", 1)

For PowerShell:
Code:

Set-ItemProperty -Path “Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings” ProxyEnable -value 0
 $key = ‘HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections’
$data = (Get-ItemProperty -Path $key -Name DefaultConnectionSettings).DefaultConnectionSettings
 $data[8] = 7
 Set-ItemProperty -Path $key -Name DefaultConnectionSettings -Value $data
 $key = ‘HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections’
$data = (Get-ItemProperty -Path $key -Name SavedLegacySettings).SavedLegacySettings
 $data[8] = 7
 Set-ItemProperty -Path $key -Name SavedLegacySettings -Value $data

Issue is, I would like to have the vbs in a .exe made with iexpress. That cannot be done since vbs isn't compilable?
So moved onto PS, and know that requires admin rights to run on our network. I was thinking the alternative to vb.NET would be the best alternative. Could anyone provide me with any insight on this, or point me to a code that will do the same functions of changing the 9th bit in the reg key?

Thanks in advance

How to assign value when a row is inserted?

$
0
0
Hi there,

I'm trying to set a second value to the cell of DataGridView, in particular as happean in the ComboBox like the DataBinding, for example:

Code:

myComboBox.DisplayMember = "NAME"
myComboBox.ValueMember = "id_value"

how you can see I have the name displayed, but when I do myComboBox.SelectedValue I get id of value selected. I want to know how I can achieve the same on the DataGridView. Actually I'm able only to add a value like this:

Code:

myDataGrid.Rows.Add({"TEST"})
how I can assign to the row added a value as in the above example?

VS 2012 VB.net DataGridView CellContentClick and CellValueChanged

$
0
0
I have a DataGridView with and editable textcolumn and editable checkbox. I attempting to write to the database as soon as the user edits, but the method seems to fire randomly between the two:

Code:


        Private Sub DGVSMT_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridSMT.CellContentClick
            'This method attempts to convert the formatted, user-specified value to the underlying cell data type.
        DataGridSMT.CommitEdit(DataGridViewDataErrorContexts.Commit)
            'If the value is successfully committed, the CellValueChanged event occurs
        End Sub

        Private Sub DGVSMT_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridSMT.CellValueChanged

        If e.ColumnIndex = 8 Then
            'do stuff if checkbox clicked
        End If
 
        If e.ColumnIndex = 7 Then
            'do stuff if text field updated
        End If

    End Sub

Sometimes when I'm editing the column 7 textbox the e.ColumnIndex = 8 checkbox IF statement will fire (but the checkbox itself in column 8 is not updated). I've tried editing the text field and hitting enter, or just clicking off the text cell to let it update. It's intermittent, sometime it works as expected, sometimes it fires the e.ColumnIndex = 8 IF statement.

Any ideas?

Need Ideas

$
0
0
For my final project for my introductory VB class, I need to make a program that I or someone else could find useful. I only know basic things on VB, I just need help on brainstorming what types of programs could be helpful and in the end could impress my teacher with the knowledge of basic VB 2008?

Character jumping not working right

$
0
0
I am trying to create a character that will move across an x/y axis that can move left, right and jump up/down. Ive got everything working right except for te jumping mechanic. When I press space, the character will jump once but after that if I press space once more the character will only move slightly downwards. You can find code here.

Help with this issue will be greatly appreciated! Thanks in advance!
Viewing all 27407 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>