读书人

JavaScript与.NET应用程序交互_实验二

发布时间: 2012-10-15 09:45:25 作者: rapoo

JavaScript与.NET应用程序交互_实验2

JavaScript与.NET应用程序交互_实验2

JavaScript调用C#函数

程序调试:王龙腾、 张明坤

文档整理:王龙腾

本系列文章由ex_net(张建波)编写,转载请注明出处。


http://blog.csdn.net/ex_net/article/details/8041253


作者:张建波 邮箱: 281451020@qq.com 电话:13577062679 欢迎来电交流!

1、新建一个C# Windows工程JsCallCsharp

2、引用Jurassic库

JavaScript与.NET应用程序交互_实验二

添加引用后效果如下:

JavaScript与.NET应用程序交互_实验二

3、 在winform上添加一个textbox,一个button

JavaScript与.NET应用程序交互_实验二

对应的代码如下:

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 JsCallCsharp{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        public delegate int delegate1(int a, int b);        public delegate void delegate2(string s);        public int add(int a, int b)        {            return a + b;        }        public void showMsg(string s)        {            System.Windows.Forms.MessageBox.Show(s);        }        private void button1_Click(object sender, EventArgs e)        {            delegate1 dlg1 = new delegate1(add);            delegate2 dlg2 = new delegate2(showMsg);            var engine = new Jurassic.ScriptEngine();            engine.SetGlobalFunction("add", dlg1);            engine.SetGlobalFunction("showMsg", dlg2);            engine.Evaluate(textBox1.Text);            engine.CallGlobalFunction<string>("fun1", 10, 20);        }    }}


首先通过委托设置C#全局函数(SetGlobalFunction),以便后面JS引擎调用相关的C#函数,然后通过脚本引擎加载执行TextBox1中的JS代码(Evaluate),再调用全局函数(CallGlobalFunction)让C#调用已经加载到JS引擎中的程序。

JS代码

function fun1(a, b){    a += b;    showMsg("a = " + a +";\r\nb = " + b + ";\r\na + b = " + add(a, b));    return 0;}


运行效果:

JavaScript与.NET应用程序交互_实验二

实验一、http://blog.csdn.net/ex_net/article/details/7821056

读书人网 >JavaScript

热点推荐