使用ObjectForScripting属性,可启用 WebBrowser 控制项所装载之 Web 网页与包含 WebBrowser 控制项之应用程式间的通讯。
这个属性可让您整合动态超文字标记语言 (DHTML) 程式码与用户端应用程式程式码。
指定给这个属性的物件可让 Web 网页指令码做为 window.external 物件,这个物件是为了存取主应用程式而提供的内建 DOM 物件。
1privatevoid btnScriptEvent_Click(object sender, EventArgs e) 2{ 3 4// This is the handler for loading the script into the Web Browser control and allowing us to interact 5// between the script in the Browser control and this form class 6 7 8// Set the ObjectForScripting property of the Web Browser control to point to this form class 9// This will allow us to interact with methods in this form class via the window.external property 10 webBrowser1.ObjectForScripting =this; 11 12string szWebBrowserText ="<html>"+ 13"<head>"+ 14"<title></title>"+ 15"</head>"+ 16"<body onkeydown=\"KeyDown()\" oncontextmenu=\"event.returnValue=false\">"+ 17 18"Please enter your name:<br/>"+ 19"<input type='text' name='Name'/><br/>"+ 20"<font onClick='window.external.ClickEvent(Name.value)'>Click Here</font>"+ 21"</body></html>"; 22 23 24 webBrowser1.DocumentText = szWebBrowserText; 25 } 26publicvoid ClickEvent(string userName) 27{ 28// Simply echo out the name that the user typed in the input box of the HTML page 29if (System.Threading.Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft ==true) 30 MessageBox.Show("Hello "+ userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading); 31else 32 MessageBox.Show("Hello "+ userName, "Managed Web Browser Sample", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); 33 34 }
这里的ObjectForScripting 属性设置为 this。注意:在From1 类的开头加入了这么一句[ComVisible(true)], 它在System.Runtime.InteropServices下,预设值为 true,指出 Managed 型别对于 COM 为可见的。
[ComVisible(true)]
public partial class Form1 : System.Windows.Forms.Form