VB.NET/C# Extension Method to Click and Element in a WebBrowser control


The following is a simple extension method for the WebBrowser control that will allow you to invoke click events on any item in the current page or sub frames that have the specified ID (and this can be modified to use wildcards, etc). In order for it to work I had to put an Application.DoEvents call at the end to force the messages to be processed, this isn't great for performance but it does the trick if not abused.

VB.Net

''' <summary>
''' Clicks the HTML elements.
''' </summary>
''' <param name="id"></param>
''' <param name="wb"></param>
<Extension()> _
Public Sub ClickElement(ByVal wb As WebBrowser, ByVal id As String)
    If wb.Document Is Nothing Then Exit Sub

    If wb.Document.Window.Frames.Count > 0 Then
        For Each hw As HtmlWindow In wb.Document.Window.Frames
            hw.Document.GetElementById(id).InvokeMember("click")
        Next
    Else
        wb.Document.Window.Document.GetElementById(id).InvokeMember("click")
    End If

    Application.DoEvents()
End Sub

C#

/// <summary>
/// Clicks the HTML elements.
/// </summary> 
/// <param name="id"></param>
/// <param name="wb"></param>
/// <remarks></remarks>
public static void ClickElement(this WebBrowser wb, string id)
{
    if (wb.Document == null)
        return;

    if (wb.Document.Window.Frames.Count > 0) 
    {
        foreach (HtmlWindow hw in wb.Document.Window.Frames) 
        {
            hw.Document.GetElementById(id).InvokeMember("click");
        }
    } 
    else 
    {
        wb.Document.Window.Document.GetElementById(id).InvokeMember("click");
    }

    Application.DoEvents();
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.