This sample demonstrates how to call C# from JavaScript. It also shows that parameters can be passed to C# methods.
First, create a Windows Forms application. Then, add a WebBrowser control to your form. Then modify the code for the form so it looks like this:
namespace WindowsFormsApplication6
{
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class Form1 : Form
{
[ComVisible(true)]
public class ScriptManager
{
private Form1 mForm;
public ScriptManager(Form1 form)
{
mForm = form;
}
public void MethodToCallFromScript()
{
mForm.DoSomething();
}
public void AnotherMethod(string message)
{
MessageBox.Show(message);
}
}
public void DoSomething()
{
MessageBox.Show("It worked!");
}
public Form1()
{
InitializeComponent();
webBrowser1.ObjectForScripting = new ScriptManager(this);
webBrowser1.DocumentText = @"<html>
<head>
<title>Test</title>
</head>
<body>
<input type=""button"" value=""Go!"" onclick=""window.external.MethodToCallFromScript();"" />
<br />
<input type=""button"" value=""Go Again!"" onclick=""window.external.AnotherMethod('Hello');"" />
</body>
</html>";
}
}
}
Note that your application may be part of a namespace other than
WindowsFormsApplication6
, but the rest of the code should work if you follow the above instructions explicitly. I created this tip/trick because somebody asked me a question and they didn't understand
this sample that I sent them to. This tip/trick makes the sample more understandable by fixing the two bugs I spotted, adding the
using
statements that weren't mentioned, and by heavily commenting the code. Hopefully the rest of you will find this of use as well.