Navigate and wait for webbrowser response with sendkeys - vb.net

Is it possible to open webpage, navigate once/click button and navigate page for the second time without having to use three buttons (everytihing is working fine with three buttons)?
I tried sleep (doesn't work) and SendKeys.SendWait (also not working).
Here is the code :
Dim browser As New WebBrowser
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With browser
browser.Name = "mybrowser"
.Dock = DockStyle.Fill
.Url = New Uri("http://pretraga2.apr.gov.rs/ObjedinjenePretrage/Search/Search")
.Visible = True
End With
Me.Controls.Add(browser)
browser.Focus()
'browser.Focus()
SendKeys.SendWait("{TAB}" & "{TAB}" & "08727988" & "{ENTER}") ' & "{TAB}" & "{ENTER}")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
browser.Focus()
SendKeys.Send("{TAB}" & "{TAB}" & "20084693" & "{ENTER}") ' & "{TAB}" & "{ENTER}")
SendKeys.SendWait("{TAB}" & "{TAB}" & "{TAB}" & "{TAB}" & "{ENTER}")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
browser.Focus()
SendKeys.Send("{TAB}" & "{TAB}" & "{TAB}" & "{TAB}" & "{ENTER}")
End Sub

Yes I think this is possible, but you have to wait till the browser finished loading. What browser-control do you use? I used SHDocVw.InternetExplorer in this example:
Public Sub browse(ByVal szURL As String, Optional ByVal bWaitTillDone As Boolean = True)
Dim nTickStart As Long
Dim nTickEnde As Long = 0
Dim i As Integer = 0
Do
Try
IE.Navigate(szURL)
If bWaitTillDone Then
nTickStart = System.Environment.TickCount
While IE.Busy
fnSleepMS(15)
nTickEnde = System.Environment.TickCount
If nTickEnde - nTickStart > IEBrowser.nMaxWaitSeconds * 1000 Then
Throw New Exception("Browse hat zu lange gedauert!")
End If
End While
End If
Exit Do
Catch ex As Exception
i += 1
If i >= 5 Then
Throw New Exception("IEBrowser.browse(): " & szURL & "--> " & ex.Message)
Else
LOG.add("IEBrowser.browse() - Versuch (" & i & ")" & ex.Message)
fnSleep(1, LOG)
End If
End Try
Loop
End Sub
Using this browser-control you can read out all ahref-Tags and Buttons and click them directly, so you are able to build up a sequence.
Hope I understood you right and this helps a bit. But please tell which browser-control you are using an in which environment (Framework + Visual Studio)

Related

call sub to change USERname color

I want to change USERname color inside RitchTextBox, I am using this code below to call the SUB but all the text now in red?
UPDATE
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & "$ ")
box.SelectionColor = Color.Black
box.AppendText(txtSend)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click
' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text)
Try
If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then
MsgBox("wright a message!", "MsgBox")
Else
client = New TcpClient(txtPCIPadd.Text, 44444)
Dim writer As New StreamWriter(client.GetStream())
txttempmsg.Text = (txtSend.Text)
writer.Write(txtUsername.Text + " # " + txtSend.Text)
AddMessage(txtUsername.Text, txttempmsg.Text + vbCrLf)
'txtmsg.Text="You:" + txtmessage.Text)
writer.Flush()
txtSend.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
When you have a problem trying to get something to work in your program. It is easier to create a test example that you can then use to figure out what is happening without dealing with a lot of other variables in your larger program. In your case I created a VB Winforms app, added a RichTextBox, two TextBox's and a Button. By doing so I am able to show that the function is working.
Public Class Form1
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & " :") 'Note added colon
box.SelectionColor = Color.Black
box.AppendText(txtSend) 'Note changed variable name to parameter name
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddMessage(txtUsername.Text, txttempmsg.Text)
End Sub
End Class
Example:

Form is sent to back after function runs

I've got the following section of code:
Public Sub SendTestEmail()
Try
Dim Mail As New MailMessage
Mail.Subject = "Test email"
Mail.To.Add(smtpTXTsendto.Text)
Mail.From = New MailAddress(smtpTXTusername.Text)
Mail.Body = "This is a test message"
Dim SMTP As New SmtpClient(smtpTXTserver.Text)
If smtpCHECKssl.Checked = True Then
SMTP.EnableSsl = True
Else
SMTP.EnableSsl = False
End If
SMTP.Credentials = New System.Net.NetworkCredential(smtpTXTusername.Text, smtpTXTpassword.Text)
SMTP.Port = smtpTXTport.Text
SMTP.Send(Mail)
MessageBox.Show("A test email has been sent." & Environment.NewLine & Environment.NewLine & "To: " & smtpTXTsendto.Text & Environment.NewLine & "From: " & smtpTXTusername.Text & "." & Environment.NewLine & Environment.NewLine & "If you did not recieve an email, please check your settings and try again.", "Test Email")
Catch ex1 As Exception
MessageBox.Show(ex1.Message)
Return
End Try
End Sub
The Sub SendTestEmail is called inside of a Background worker.
The odd issue I'm having, as that when a MessageBox appears, and I click OK the form gets sent to the back of the screen, behind all applications ...
I've tried adding a Me.focus, but it gives me issues about Cross Tread violations.
Any ideas why this is happening?
Background Worker Code:
Private Sub BGWSendTestEmail_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BGWSendTestEmail.DoWork
SendTestEmail()
End Sub
Private Sub BGWSendTestEmail_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWSendTestEmail.RunWorkerCompleted
If (e.Cancelled) Then
MsgBox("Something went wrong!")
Else
GroupBoxTesting.Visible = False
Me.Enabled = True
End If
End Sub
Private Sub SMTPButtonTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMTPButtonTest.Click
GroupBoxTesting.Visible = True
Me.Enabled = False
BGWSendTestEmail.RunWorkerAsync()
End Sub
Change BGWSendTestEmail_RunWorkerCompleted to something like this and remove exception handling from SendTestEmail
Me.Enabled = True ' Always enable form first after completed
If e.Error Is Nothing Then
If Not e.Cancelled Then
MessageBox.Show("A test email has been sent." _
& Environment.NewLine _
& Environment.NewLine _
& "To: " & smtpTXTsendto.Text _
& Environment.NewLine _
& "From: " & smtpTXTusername.Text _
& "." & Environment.NewLine _
& Environment.NewLine _
& "If you did not recieve an email, please check your settings and try again.", _
"Test Email")
GroupBoxTesting.Visible = False 'Maybe put this also into start of method?
Else
MsgBox("Something went wrong!")
End If
Else
MessageBox.Show("Email sending failed. Exception: " & e.Error.Message)
End If
If you debug this program your debugger will attach exceptions in do_work method, but if you run it without debugger then exceptions are handled at completed method.

Why does loop doesnt stop at .showdialog in formloadevent

Hello here is a very strange bug I cannot solve. I have a while loop in my formload that looks this way :
While loginOK = False And pstop = False
LoginForm1.ShowDialog()
If NewReg = True Then
While RegErfolgreich = False
Registrierung.ShowDialog()
Dim con As New SqlConnection(My.Settings.SLXADRIUMDEVConnectionString)
con.Open()
Dim cmd = New SqlCommand("Insert Into sysdba.PL_Userverwaltung (Benutzername, Passwort, [E-Mail-Adresse], Profil_OK) Values('" & RegBenutzername & "', '" & RegPassword & "', '" & RegEMailAdresse & "', 'f')", con)
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
End If
End While
Else
NewReg = False
End If
End While
The problem is that after closing loginform1 he jumps back in the loop, and when he starts looping again he opens loginform1 and closes it instantly. and loops again in the while loop.
That means I have a endless loop, which shows the loginform1 and closes it a millisecond later.
One thing to mention is that a friend of mine opened my project in an older vs studio version and this mysterious bug doesnt happen??
Hope for input cheers
EDIT:
Here is loginform1 code
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
Startseite.LoginUsername = UsernameTextBox.Text
Startseite.LoginPassword = PasswordTextBox.Text
Startseite.loginOK = True
Me.Close()
Else
MsgBox("Bitte Benutzername und Passwort eingeben!")
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Startseite.pstop = True
Me.Close()
End Sub
Private Sub LoginForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.Benutzername <> "" And My.Settings.Passwort <> "" Then
'MsgBox(My.Settings.Benutzername & " " & My.Settings.Passwort)
UsernameTextBox.Text = My.Settings.Benutzername
PasswordTextBox.Text = My.Settings.Passwort
End If
End Sub
Private Sub lblNeuRegistrieren_Click(sender As Object, e As EventArgs) Handles lblNeuRegistrieren.Click
Startseite.NewReg = True
Me.Close()
End Sub
About your error, probably you didn't initialize your startseite variable to be your main form, loginOK And pstop never get changed and that's why the loop never stops. But on the rest of your code, some general tips.
This is unnecesary
If NewReg = True Then
''
Else
NewReg = False
End If
If NewReg is not true, then it's false by definition. Should be
If NewReg Then
''
End If
Also, overloading the showDialog on loginForm1 is a better solution than adding a yourmainclass object on the second form. It is easier to debug and provides better reusability.
try exiting loop on message box
If cmd.ExecuteNonQuery() = 1 Then
My.Settings.Benutzername = RegBenutzername
My.Settings.Passwort = RegPassword
My.Settings.Save()
Me.Close()
RegErfolgreich = True
Else
MsgBox("Es ist ein Fehler aufgetreten.")
Exit While
End If

Making checked boxes put multiline text into a label

So I have 4 check boxes and if one of them is checked, I would like to put that text into a label.
My problem is when one box is checked, it just has that text in the label but not the other checked ones. I want it to have a new line for each box that is checked to put new line text into the label.
How would I be able to have the program go through the check boxes, and if they are checked put that text into a label and for the next box checked start a new line and put that text there?
To be put under a button click event.
Quick and dirty, but if I understand what you are asking for this should work.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = ""
If (CheckBox1.Checked) Then
Label1.Text &= CheckBox1.Text & vbCrLf
End If
If (CheckBox2.Checked) Then
Label1.Text &= CheckBox2.Text & vbCrLf
End If
If (CheckBox3.Checked) Then
Label1.Text &= CheckBox3.Text & vbCrLf
End If
If (CheckBox4.Checked) Then
Label1.Text &= CheckBox4.Text & vbCrLf
End If
End Sub
Put all your CheckBoxes in the same container. In this example, they are all contained within Panel1. This gets all the Text properties of the CheckBoxes which are checked, and puts the Text in Label1.Text. When nothing is selected, an Exception is thrown (Sequence contains no elements).
Try
Label1.Text = Panel1.Controls.OfType(Of CheckBox). _
Where(Function(arg) arg.Checked). _
Select(Function(arg) arg.Text). _
Aggregate(Function(aggregate, nextItem) aggregate & Environment.NewLine & nextItem)
Catch ex As Exception
Label1.Text = "Nothing selected"
End Try
Try this code,
[Note: Tested with IDE]
Private Sub Common_Cheked_Change_Handler(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles _
CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, _
CheckBox3.CheckedChanged, CheckBox4.CheckedChanged
Label1.Text = String.Empty
Label1.Text = If(CheckBox1.Checked = True, CheckBox1.Text & vbCrLf, String.Empty) & _
If(CheckBox2.Checked = True, CheckBox2.Text & vbCrLf, String.Empty) & _
If(CheckBox3.Checked = True, CheckBox3.Text & vbCrLf, String.Empty) & _
If(CheckBox4.Checked = True, CheckBox4.Text, String.Empty)
End Sub

Add text to richbox without deleting

i try to mekae a program how tell me in a richbox what i do for examle, i have 4 CheckBoxes when i click one enable in RichBox must apear
apple enabled...
pear disabled...
So i have apple pear carrot peanut
and richbox need look like,
Pear disabled...
Carrot disabled...
Peanut Enabled...
Pear Enabled....
SUBMIT SUCCES !
Pear disabled...
I try that for every checkbox but when i check one richbox is reset and apear only one line
If CheckBox2.Checked = True Then
RichTextBox1.Text = "pear enabled..."
Else
RichTextBox1.Text = "pear disabled..."
End If
What can i do ?
Thanks !
Maybe you need this:
If CheckBox2.Checked = True Then
RichTextBox1.Text &= "pear enabled..." & Environment.NewLine()
Else
RichTextBox1.Text &= "pear disabled..." & Environment.NewLine()
End If
You could simply use the SelectedText property of the Rich Text Box control to append text properly. Please see the following code..
Public Class Form1
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
If (CheckBox1.Checked) Then
RichTextBox1.SelectedText = CheckBox1.Text & " Enabled" & vbCrLf
Else
RichTextBox1.SelectedText = CheckBox1.Text & " Disabled" & vbCrLf
End If
End Sub
Private Sub CheckBox2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox2.CheckedChanged
If (CheckBox1.Checked) Then
RichTextBox1.SelectedText = CheckBox2.Text & " Enabled" & vbCrLf
Else
RichTextBox1.SelectedText = CheckBox2.Text & " Disabled" & vbCrLf
End If
End Sub
Private Sub CheckBox3_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox3.CheckedChanged
If (CheckBox1.Checked) Then
RichTextBox1.SelectedText = CheckBox2.Text & " Enabled" & vbCrLf
Else
RichTextBox1.SelectedText = CheckBox2.Text & " Disabled" & vbCrLf
End If
End Sub
End Class
The word you're looking for is "append" text.
RichTextBox1.AppendText("pear enabled...")