码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-04 13:17:19      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:xhtml   org   sage   c#   注意   nbsp   脚本   .text   init   

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

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

这里需要注意js访问外部windows应用程序方法,需要代用windows对象的external

例子:window.external.CSharpfunction(xx,xx,xx);
 1 <!DOCTYPE html>
 2 
 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <meta http-equiv="Content-Language" content="zh-cn">
 6     <script language="javascript" type="text/javascript">
 7               <!-- 提供给C#程序调用的方法 -->
 8               function messageBox(message)
 9               {
10                     alert(message);
11              }
12     </script>
13 </head>
14 
15 <body>
16     <!-- 调用C#方法 -->
17     <button onclick="window.external.MyMessageBox(‘javascript访问C#代码‘)">
18         javascript访问C#代码
19     </button>
20 </body>
21 </html>

二、创建C#windows窗体应用

技术分享图片

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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace WinFormJSDemo
11 {
12     //设置Com对外可访问
13     [System.Runtime.InteropServices.ComVisible(true)]
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19             System.IO.FileInfo file = new System.IO.FileInfo("JavaScript//index.html");
20 
21             // WebBrowser控件显示的网页路径
22             webBrowser1.Url = new Uri(file.FullName);
23 
24             // 将当前类设置为可由脚本访问
25             webBrowser1.ObjectForScripting = this;
26         }
27 
28 
29         //被外部js调用的方法
30         public void MyMessageBox(string message)
31         {
32 
33             MessageBox.Show(message);
34         }
35 
36         private void button1_Click(object sender, EventArgs e)
37         {
38             // 调用JavaScript的messageBox方法,并传入参数
39             object[] objects = new object[1];
40 
41             objects[0] = "C#访问JavaScript脚本";
42 
43             webBrowser1.Document.InvokeScript("messageBox", objects);
44         }
45     }
46 }

运行结果:

C#调用JavaScript方法

技术分享图片

JavaScript调用C#方法:

技术分享图片

 

参考:http://www.cnblogs.com/xds/archive/2007/03/02/661838.html

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

标签:xhtml   org   sage   c#   注意   nbsp   脚本   .text   init   

原文地址:http://www.cnblogs.com/JiYF/p/7976391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!