Set the focus to a HTML Textbox or Button in a WebBroswer control

user1473832 picture user1473832 · Jun 24, 2012 · Viewed 26.2k times · Source

I am opening a website in a WebBrowser control using VB.NET 2008. On the fourth page of the website, I want to focus the control by triggering the tab key programmatically. I am using the following code:

If adtxt.Text = "http://aojsl.com/dfassfeed2.php" Then
    System.Windows.Forms.SendKeys.Send("{TAB}")
End If

However, my code is unable to trigger the tab key. Does anyone know how to make this work?

Answer

Jeremy Thompson picture Jeremy Thompson · Jun 24, 2012

Method 1

Private Sub Form_Load()
    WebBrowser1.Navigate "http://www.google.com/"
    Do
     Thread.Sleep(100)
    Loop While webBrowser1.IsBusy = True
End Sub 

Private Sub Command1_Click()
    WebBrowser1.Document.All("q").focus 'Set focus to the search text field
End Sub

Private Sub Command2_Click()
    WebBrowser1.Document.All("btnI").focus 'Set focus to the google "I Am feeling lucky button"
End Sub

Method 2

I converted it to VB.Net from this MSDN thread: Focus issues with System.Windows.Controls.WebBrowser

You will need to change the ActiveElement in webBrowser.Document.ActiveElement.Focus() to the textbox or button.

Public Partial Class Form1
    Inherits Form
  Public Sub New()
    InitializeComponent()
    Dim host As New WindowsFormsHost()
    im webBrowser As New WebBrowser()
    host.Child = webBrowser
    elementHost1.Child = host

    webBrowser.Navigate(New Uri("http://www.google.com"))
    Me.Activated += Function() Do
      Console.WriteLine(Me.ActiveControl)
      If webBrowser.Document <> Nothing Then
        If Me.ActiveControl = elementHost1 AndAlso webBrowser.Document.ActiveElement <> Nothing Then
          webBrowser.Document.ActiveElement.Focus()
        End If
      End If
    End Function
  End Sub
End Class

Method 3

Another way might be to do it in the HTML, eg:

OnLoad="document.myform2.mybutton.focus();">