WinForm程序嵌入一个WebBrowser控件,发现WinForm中与Web中方法居然是可以相互调用的。
找到的原来的一个例子中,有System.Security.PemissionSet提示 不是特性 类,直接去掉,测试也能成功。
namespace WindowsFormsApplication3
{
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;//将 WebBrowser 控件的 AllowWebBrowserDrop 属性设置为 false,以防止 WebBrowser 控件打开拖放到其上的文件。
webBrowser1.IsWebBrowserContextMenuEnabled = false;//将该控件的 IsWebBrowserContextMenuEnabled 属性设置为 false,以防止 WebBrowser 控件在用户右击它时显示其快捷菜单.
webBrowser1.WebBrowserShortcutsEnabled = false;//将该控件的 WebBrowserShortcutsEnabled 属性设置为 false,以防止 WebBrowser 控件响应快捷键。
webBrowser1.ScriptErrorsSuppressed = true;//将该控件的 ScriptErrorsSuppressed 属性设置为 true,以防止 WebBrowser 控件显示脚本代码问题的错误信息。
webBrowser1.ObjectForScripting = this;
string url = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.Replace("\\bin\\Debug", "") + "HTMLPage1.htm";
webBrowser1.Navigate(url);
}
public string InvokeFormMethod(string message)
{
MessageBox.Show("这是从WinForm弹出的提示!", "WinForm");
return "Charles2008";
}
private void button1_Click(object sender, EventArgs e)
{
this.webBrowser1.Document.InvokeScript("msgalert", new string[] { "Called Javascript code" });
}
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script>
function msgalert(msg) {
alert(msg);
}
</script>
</head>
<body>
<input type="button" value="在Web页面中,调用WinForm函数" οnclick="alert(window.external.InvokeFormMethod('从Web发起的调用'))" />
</body>
</html>