一、建立网页
<html>
<head> <meta http-equiv="Content-Language" content="zh-cn">
<script language="javascript" type="text/javascript">
<!-- 提供给C#程序调用的方法 -->
function messageBox(message)
{
alert(message);
}
</script>
</head>
<body>
<!-- 调用C#方法 -->
<button onclick="window.external.MyMessageBox('javascript访问C#代码')">
javascript访问C#代码</button>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<script language="javascript" type="text/javascript">
<!-- 提供给C#程序调用的方法 -->
function messageBox(message)
{
alert(message);
}
</script>
</head>
<body>
<!-- 调用C#方法 -->
<button onclick="window.external.MyMessageBox('javascript访问C#代码')">
javascript访问C#代码</button>
</body>
</html>
二、建立Windows应用程序
1.创建Windows应用程序项目
2.在Form1窗体中添加WebBrowser控件
3.在Form1类的上方添加
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
这是为了将该类设置为com可访问。如果不进行该声明将会出错。出错信息如下图所示:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
4.初始化WebBrowser的Url与ObjectForScripting两个属性。
Url属性:WebBrowser控件显示的网页路径
ObjectForScripting属性:该对象可由显示在WebBrowser控件中的网页所包含的脚本代码访问。
将Url属性设置

本文详细介绍了如何在C# WinForm程序中利用WebBrowser控件与JavaScript进行交互,包括C#调用JavaScript函数和JavaScript调用C#方法的实现步骤,以及需要注意的权限设置和对象设置。

1292

被折叠的 条评论
为什么被折叠?



