您的位置:首页 > Web前端 > JavaScript

C# windows程序应用与JavaScript 程序交互实现例子

2017-12-04 11:47 721 查看


C# windows程序应用与JavaScript 程序交互实现例子

最近项目中又遇到WinForm窗体内嵌入浏览器(webBrowser)的情况,而且涉及到C#与JavaScript的相互交互问题,下面就是一个交互例子,仅供参考


一、建立网页代码(包含js方法代码和访问外部windows应用事件)

这里需要注意js访问外部windows应用程序方法,需要代用windows对象的external
例子:window.external.CSharpfunction(xx,xx,xx);

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<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>


二、创建C#windows窗体应用




代码:需要注意的是需要给form1类加上对com的可访问性设置  [System.Runtime.InteropServices.ComVisible(true)]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinFormJSDemo
{
//设置Com对外可访问
[System.Runtime.InteropServices.ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.IO.FileInfo file = new System.IO.FileInfo("JavaScript//index.html");

// WebBrowser控件显示的网页路径
webBrowser1.Url = new Uri(file.FullName);

// 将当前类设置为可由脚本访问
webBrowser1.ObjectForScripting = this;
}

//被外部js调用的方法
public void MyMessageBox(string message)
{

MessageBox.Show(message);
}

private void button1_Click(object sender, EventArgs e)
{
// 调用JavaScript的messageBox方法,并传入参数
object[] objects = new object[1];

objects[0] = "C#访问JavaScript脚本";

webBrowser1.Document.InvokeScript("messageBox", objects);
}
}
}


运行结果:


C#调用JavaScript方法




JavaScript调用C#方法:



 

参考:http://www.cnblogs.com/xds/archive/2007/03/02/661838.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐