新建一个window窗体应用程序
引用 com 的 Microsoft Script Control
拖二个textbox,一个button

双击run button.
将Form1换成:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]//让com可以调用Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
init();
}
#region msscript
MSScriptControl.ScriptControlClass sc;
void init()
{
sc = new MSScriptControl.ScriptControlClass();
sc.Language = "javascript";//设置语言
sc.AllowUI = true;//可ui交互
sc.SitehWnd = this.Handle.ToInt32();//交互时,在本窗口之上显示
//添加對象
sc.AddObject("window", this, false);//window 在js中的变量名,this,添加的对象
//添加代碼
sc.AddCode("function alert(message){window.alert(message);}");//添加js方法alert,做用是调用C#中Form1.alert方法
}
//显示信息
public void alert(string mes)
{
MessageBox.Show(mes);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sc.AddCode(textBox1.Text);
object obj = null;
StringBuilder sb = new StringBuilder();
if (obj != null)
sb.AppendLine(obj.ToString());
//显示代码的所有方法
if (sc.Procedures != null)
for (int i = 1; i <= sc.Procedures.Count; i++)
{
MSScriptControl.Procedure m = sc.Procedures[i];
sb.Append(m.Name).Append(":").Append(m.GetType()).AppendLine();
}
textBox2.Text = sb.ToString();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
#endregion msscript
}
效果:

C#中调用js,将方法换成,点下run后,下面的textbox显示结果12
private void button1_Click(object sender, EventArgs e)
{
sc.AddCode("function sum(one,two){return one+two;}");//添加代码
object[] para = new object[] { 1,11};//参数
object obj= sc.Run("sum",ref para);//调用js的sum方法
textBox2.Text = obj.ToString();
}

2635

被折叠的 条评论
为什么被折叠?



