This article describes how Javascript embedded in an HTML file displayed in .Net's WebBrowser control calls C# code. It is now very common to embed web pages in client programs, such as Tencent's news pop-up box.
.Net’s WebBrowser should still use IE’s kernel. In IE, the window object has an external attribute, which provides an external interface. Host code can be executed. To call a C# method through this property, its host object must be ComVisible. For example, we place a WebBrowser control on a Form and prepare a method OpenForm for js to call.
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Main : KSBiz.UI.KSForm
{
public Main()
{
InitializeComponent();
}
//The rest is omitted
public void OpenForm(string s)
{
BasicInfo.CustomerList f = new StockManage.BasicInfo.CustomerList();
f.Show();
f.MdiParent = this;
webBrowser1. Visible = false;
}
}
Prepare another html file:
In the HTML file, you can call C# through the above method method.
In the FormLoad event, set the url for the WebBrowser control and set the host for script execution:
private void Main_Load(object sender, EventArgs e)
{
System.IO.FileInfo file = new System.IO.FileInfo("top.htm");
// The web page path displayed by the WebBrowser control
webBrowser1.Url = new Uri(file.FullName);
// Set the current class to be accessible by scripts
webBrowser1.ObjectForScripting = this;
}
That’s fine.