JavaScript与.NET应用程序交互_实验2
1、新建一个C# Windows工程JsCallCsharp
2、引用Jurassic库
添加引用后效果如下:
3、 在winform上添加一个textbox,一个button
对应的代码如下:
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;}
运行效果:
实验一、http://blog.csdn.net/ex_net/article/details/7821056