这两天写一个程序,winform的webbrowser装载htm文件,然后和winform窗体交互。
1.page.htm文件源代码





































2.TestForm源代码
private void TestForm_Load(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("C:/page.htm");//指定要载入的网页
}
private void ButtonF1(object sender, EventArgs e)
{
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
win.execScript("F1('日本')", "javascript");//调用函数F1
}
private void ButtonF2(object sender, EventArgs e)
{
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
win.execScript("F2()", "javascript");//调用函数F2
}
private void ButtonF3(object sender, EventArgs e)
{
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLElement el = (mshtml.IHTMLElement)win.document.all.item("Country", null);//取得页面上的Country Dom对象
el.innerText="荷兰";//直接修改页面上Country对象的属性
}
//调用webbrowser的DocumentCompleted事件来自动修改页面属性,修改属性的方法可以用上面的三种方法。我用的是第一种方法
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
win.execScript("F1('日本')", "javascript");//调用函数F1
}