C# windows程序应用与JavaScript 程序交互实现例子
来源:互联网 发布:scratch编程实例 编辑:程序博客网 时间:2024/06/05 19:41
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
阅读全文
0 0
- C# windows程序应用与JavaScript 程序交互实现例子
- c# 与桌面程序交互
- JavaScript与C# Windows应用程序交互(转)
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互
- JavaScript与C# Windows应用程序交互方法
- C# WinForm程序如何与js交互
- C# WinForm程序如何与js交互??
- C# WinForm程序如何与js交互
- C# WinForm程序如何与js交互
- C# WinForm程序如何与js交互
- C# WinForm程序如何与js交互
- C# WinForm程序如何与js交互
- 『数据稽核』的相关知识
- QQ浏览器app应用专区推荐系统
- Ajax中send方法参数的使用
- java.lang.NoClassDefFoundError: org/springframework/core/MethodClassKey
- 关于处理样本不平衡问题的Trick整理
- C# windows程序应用与JavaScript 程序交互实现例子
- 搞定这8个实战项目,秒杀80%人工智能工程师面试者
- 双系统下,解决ubuntu无法访问windows建立的硬盘
- 栈的数据类型定义
- 物料管理自动记账详解
- 【Scikit-Learn 中文文档】模型持久化
- 设置Android通知栏Notification的字体/图标颜色随背景色变化而变化
- js 中//<![CDATA[ 意义
- 存储过程第一讲:存储过程的创建,删除,修改,调用,查看