今天写了三个简单例子,玩一玩这个ReoScript引擎
首先看界面
分别是三个按钮,第一个按钮,弹出一个提示框,第二个创建一个窗体,第三个从文件中读出脚本并执行
主要代码如下
using System; using System.IO; using System.Text; using System.Windows.Forms; using unvell.ReoScript; namespace ReoScript_BuildUI { public partial class Form1 : Form { private readonly ScriptRunningMachine _srm = new ScriptRunningMachine(); public Form1() { InitializeComponent(); } //弹出提示框 private void button1_Click(object sender, EventArgs e) { CompiledScript script = _srm.Compile("alert('Hello World');"); _srm.RunCompiledScript(script); } //导入.net命名空间,并创建一个窗体 private void button2_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.AppendLine(" import System.Windows.Forms.*; "); sb.AppendLine(" import System.Drawing.*; "); sb.AppendLine(" "); sb.AppendLine(" var f = new Form() { "); sb.AppendLine(" text: 'ReoScript Form', startPosition: 'CenterScreen', "); sb.AppendLine(" resize: function() { link.location = { x: (this.width - link.width) / 2, y : link.top }; }, "); sb.AppendLine(" load: function() { updateLabelText(); } "); sb.AppendLine(" }; "); sb.AppendLine(" "); sb.AppendLine(" var link = new LinkLabel() { "); sb.AppendLine(" text: 'click me to close window', autoSize: true, location: { x: 75, y: 100 }, "); sb.AppendLine(" click: function() { f.close(); f = null; }, "); sb.AppendLine(" }; "); sb.AppendLine(" "); sb.AppendLine(" var stateCount = 10, stateIndex = 0; "); sb.AppendLine(" "); sb.AppendLine(" var lab = new Label() { "); sb.AppendLine(" text: '='.repeat(stateCount), location: { x: 100, y: 50 }, autoSize: true, "); sb.AppendLine(" }; "); sb.AppendLine(" "); sb.AppendLine(" function updateLabelText() { "); sb.AppendLine(" lab.text = '='.repeat(stateIndex) + '>' + '='.repeat(stateCount - stateIndex); "); sb.AppendLine(" if(stateIndex<stateCount) stateIndex++; else stateIndex = 0; "); sb.AppendLine(" "); sb.AppendLine(" if(f != null) setTimeout(updateLabelText, 100); "); sb.AppendLine(" } "); sb.AppendLine(" "); sb.AppendLine(" f.controls.addRange([link, lab]); "); sb.AppendLine(" f.showDialog(); "); _srm.WorkMode |= MachineWorkMode.AllowDirectAccess | MachineWorkMode.AllowCLREventBind | MachineWorkMode.AllowImportTypeInScript; _srm.Run(sb.ToString()); } //从文件中导入脚本并执行 private void button3_Click(object sender, EventArgs e) { var path = Application.StartupPath + @"\Script.txt"; if (File.Exists(path)) { var file = new FileInfo(path); _srm.WorkMode |= MachineWorkMode.AllowDirectAccess | MachineWorkMode.AllowCLREventBind | MachineWorkMode.AllowImportTypeInScript; _srm.Run(file); } } } }
说一说Run和RunCompiledScript这两个方法的区别,Run执行脚本每次都要重新编译,而RunCompiledScript只会编译一次,后面再重复调用的时候,可以提高执行效率,比如说在一个循环里面重复执行一段脚本
CompiledScript code = srm.Compile(script); ... for (int i = 0; i < 10; i++) { srm.RunCompiledScript(code); }
文中源代码可以在这里下载