How to capture button click event of webpage (opened inside WebBrowser Control) in WPF form?

Consider a scenario where I have a WebBrowser Control in WPF application.
A web page is loaded inside WebBrowser Control. The web page contains a button.
The web page is of ASP.NET application.

I want to capture the button click event of the webpage into WPF Form (which hosts WebBrowser Control). Is there any way to achieve this functionality ?




Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here is code that should do exactly what you want with comments to explain what is going on:

public partial class MainWindow : Window

    /// <summary>
    /// This is a helper class.  It appears that we can't mark the Window as ComVisible
    /// so instead, we'll use this seperate class to be the C# code that gets called.
    /// </summary>
    public class ComVisibleObjectForScripting
        public void ButtonClicked()
            //Do whatever you need to do.  For now, we'll just show a message box
            MessageBox.Show("Button was clicked in web page");

    public MainWindow()
        //Pass an instance of our helper class as the target object for scripting
        webBrowser1.ObjectForScripting = new ComVisibleObjectForScripting();

    private void Window_Loaded(object sender, RoutedEventArgs e)
        //Navigate to your page somehow

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
        //Once the document is loaded, we need to inject some custom JavaScript.

        //Here is the JavaScript
        var javascript = @"
//This is the JavaScript method that will forward the click to the WPF app
function htmlButtonClicked()
    //Do any other we just always call to the WPF app

//Find the button that you want to watch for clicks 
var searchButton = document.getElementById('theButton');

//Attach an onclick handler that executes our function

        //Grab the current document and cast it to a type we can use
        //NOTE: This interface is defined in the MSHTML COM Component
        //       You need to add a Reference to it in the Add References window
        var doc = (IHTMLDocument2)webBrowser1.Document;

        //Once we have the document, execute our JavaScript in it

Some of this was taken from

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x