阿里妈妈,帮你实现网络赚钱梦,流量变成现金!
在Winform程序中,通过WebBrowser控件可以让Javascript 和 C#进行交互。要让JS调用C#方法,需要在类上设置ComVisible,然后还要设置WebBrowser的ObjectForScripting属性。
JS中调用只需使用:window.external.方法名
具体代码如下:
复制内容到剪贴板
程序代码
程序代码using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Lwolf
{
public partial class Form1 : Form
{
//此类必须对 COM 可见,才能从Javascript中调用。
[ComVisible(true)]
public class ScriptManager
{
public ScriptManager()
{
}
//此方法可在JS中调用
public void CallFromJS(string message)
{
MessageBox.Show(message);
}
}
public Form1()
{
InitializeComponent();
webBrowser1.ObjectForScripting = new ScriptManager();
webBrowser1.DocumentText = @"<html>
<head>
<title>Test</title>
</head>
<body>
<input type=""button"" value=""点击"" onclick=""window.external.CallFromJS('TEST');"" />
</body>
</html>";
}
}
}
using System.Windows.Forms;
namespace Lwolf
{
public partial class Form1 : Form
{
//此类必须对 COM 可见,才能从Javascript中调用。
[ComVisible(true)]
public class ScriptManager
{
public ScriptManager()
{
}
//此方法可在JS中调用
public void CallFromJS(string message)
{
MessageBox.Show(message);
}
}
public Form1()
{
InitializeComponent();
webBrowser1.ObjectForScripting = new ScriptManager();
webBrowser1.DocumentText = @"<html>
<head>
<title>Test</title>
</head>
<body>
<input type=""button"" value=""点击"" onclick=""window.external.CallFromJS('TEST');"" />
</body>
</html>";
}
}
}
其它关于Webbrowser的文章:
http://www.lwolf.cn/blog/article/code/csharp-web-js.htm
http://www.lwolf.cn/blog/article/code/webbrowser-winform.htm
发表评论
上一篇:
下一篇: 
文章来自:
文章标签:
网摘收录:
回复
|
|
]