Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms - How do I execute C# application code from inside WebBrowser control?

I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form.

For example, a button in the HTML might call the Close() method on the form.

Target platform: C# and Windows Forms (any version)

like image 473
Brian Lyttle Avatar asked Nov 28 '22 13:11

Brian Lyttle


1 Answers

I've implemeted this in a few applications in the past, here's how: (NB: the example below is not production ready and should be used as a guide only).

First create a normal .NET class (public) that contains public methods that you wish to call from Javasvcipt running in your web browser control.

Most importantly it must be decorated with the ComVisible(true)] attribute from the System.Runtime.InteropServices namespace (Javascript in IE is COM based). It can be called anything, I've called it "External" to make things clearer.

using System.Runtime.InteropServices;

[ComVisible(true)]
public class External
{
    private static MainWindow m_mainWindow = null;

    public External(MainWindow mainWindow)
    {
        m_mainWindow = mainWindow; 
    }

    public void CloseApplication()
    {
        m_mainWindow.Close();
    }


    public string CurrentDate(string format)
    {
        return DateTime.Now.ToString(format);  
    }
}

Next in the .NET form containing your web browser control create an instance of the COMVisible class, then set the web browser controls ObjectForScripting to that instance:

    private void MainWindow_Load(object sender, EventArgs e)
    {
         m_external = new External(this);

         browserControl.ObjectForScripting = m_external; 
    }

Finally, in your Javascript running in the web browser control, you access the .NET methods via the window.external object. In this case window.external actually references (indirectly via a COM interop wrapper) the "External" object created above:

// Javascript code
function CloseButton_Click()
{
    if (window.external)
    {
        window.external.CloseApplication();
    }
}

Be aware that calls from Javascript to .NET pass through the COM interop layer and so querying of the default interface, marshalling of parameters etc must occur. In other words it can be relatively SLOW, so do some performance testing if you plan to make multiple calls for example from within a loop.

Also, just for future reference, calling Javascript code from .NET is simpler, just use the Document.InvokeScript method:

    browserControl.Document.InvokeScript("jScriptFunction", new object[] { "param1", 2, "param2" });
like image 158
Ash Avatar answered Dec 07 '22 22:12

Ash