C # Call the JavaScript Engine

Source: Internet
Author: User
Tags microsoft website
The following two sections describe the implementation and application.
1. Use MSScriptControl to Download Windows Script Control from Microsoft website. It is an ActiveX (R) Control, so I used Interop in. NET. After the download and installation are complete, create a C # Windows application project, select the reference node in solution Resource Manager, right-click and choose add reference from the shortcut menu, and the Add reference dialog box is displayed, click Browse to find the directory for installing Windows Script Control and select msscript. ocx file. A MSScriptControl component is added to the reference node. The following are all objects after Interop.

Using System;

Using MSScriptControl; using System. text; namespace ZZ {// <summary> // Script Type // </summary> public enum ScriptLanguage {// <summary> // JScript Language /// </summary> JScript, /// <summary> /// VBscript language /// </summary> VBscript, /// <summary> /// JavaScript script language /// </summary> JavaScript }/// <summary> /// script running error proxy /// </summary> public delegate void RunErrorHandler (); /// <summary> /// script running timeout proxy /// </Summary> public delegate void RunTimeoutHandler (); /// <summary> /// ScriptEngine class /// </summary> public class ScriptEngine {******* ScriptControl msc; // define the script running error event public event RunErrorHandler RunError; // define the script running timeout event public event RunTimeoutHandler RunTimeout; /// <summary> /// constructor /// </summary> public ScriptEngine (): this (ScriptLanguage. VBscript) {}/// <summary> /// constructor // </summary> // /<Param name = "language"> Script Type </param> public ScriptEngine (ScriptLanguage language) {this. msc = new ScriptControlClass (); this. msc. useSafeSubset = true; this. msc. language = language. toString (); (DScriptControlSource_Event) this. msc ). error + = new DScriptControlSource_ErrorEventHandler (ScriptEngine_Error); (DScriptControlSource_Event) this. msc ). timeout + = new DScriptControlSource_TimeoutEventHandler (ScriptEngine_Timeout );} /// <summary> /// run the Eval method /// </summary> /// <param name = "expression"> expression </param> /// <param name = "codeBody"> function body </param> // <returns> return value object </returns> public object Eval (string expression, string codeBody) {msc. addCode (codeBody); return msc. eval (expression );} /// <summary> /// run the Eval method /// </summary> /// <param name = "language"> script language </param> /// <param name = "expression "> Expression </param> /// <param name =" codeBody "> function body </param> /// <returns> returned object </returns> public object Eval (scriptLanguage language, string expression, string codeBody) {if (this. language! = Language) this. language = language; return Eval (expression, codeBody );} /// <summary> /// Run the Run method /// </summary> /// <param name = "mainFunctionName"> name of the entry function </param> /// <param name = "parameters"> parameter </param> /// <param name = "codeBody"> function body </param> /// <returns> returned object </ returns> public object Run (string mainFunctionName, object [] parameters, string codeBody) {this. msc. addCode (codeBody); return msc. run (MainFunctionName, ref parameters );} /// <summary> /// Run the Run method /// </summary> /// <param name = "language"> script language </param> /// <param name = "mainFunctionName"> name of the entry function </param> // <param name = "parameters"> parameter </param> /// <param name = "codeBody"> function body </param> /// <returns> returned object </returns> public object Run (ScriptLanguage language, string mainFunctionName, object [] parameters, string codeBody) {if (this. language! = Language) this. language = language; return Run (mainFunctionName, parameters, codeBody );} /// <summary> /// discard all Script code and objects that have been added to ScriptControl. // </summary> public void Reset () {this. msc. reset () ;}//< summary> /// obtain or set the script Language /// </summary> public ScriptLanguage Language {get {return (ScriptLanguage) Enum. parse (typeof (ScriptLanguage), this. msc. language, false);} set {this. msc. language = value. to String () ;}/// <summary> // obtain or set the script execution time, unit: millisecond // </summary> public int Timeout {get {return this. msc. timeout;} set {this. msc. timeout = value ;}/// <summary> // set whether to display the user interface elements /// </summary> public bool AllowUI {get {return this. msc. allowUI;} set {this. msc. allowUI = value ;}/// <summary> // whether the host application has confidentiality requirements // </summary> public bool UseSafeSubset {get {return this. msc. useSafeSubset;} set {this. Msc. UseSafeSubset = true ;}/// <summary> // triggered by the RunError event /// </summary> private void OnError () {if (RunError! = Null) RunError () ;}/// <summary> // The OnTimeout event is triggered /// </summary> private void OnTimeout () {if (RunTimeout! = Null) RunTimeout ();} private void ScriptEngine_Error () {OnError ();} private void ScriptEngine_Timeout () {OnTimeout ();}}} the above packaging defines a ScriptLanguage enumeration, which makes it easier to operate. In addition, the script engine includes Error events and Timeout events, which can be registered based on actual usage. II. The script engine demonstrates that I have created a form program to test whether to enable the AllowUI attribute, set the timeout time, and select a method for calling the script engine. The code of the test program is long. The following lists the main parts: using System; using System. drawing; using System. collections; using System. componentModel; using System. windows. forms; using System. data; namespace ZZ {public class Form1: System. windows. forms. form {private ScriptEngine scriptEngine; private System. windows. forms. checkBox checkBoxAllowUI; private System. windows. forms. textBox textBoxResult; private System. windows. forms. numericUpDown n UmericUpDownTimeout; private System. windows. forms. textBox textBoxCodeBody; private System. windows. forms. button buttonRun; private System. windows. forms. button buttonCancel; private System. windows. forms. comboBox comboBoxScript; private System. windows. forms. textBox textBoxParams; private System. windows. forms. radioButton radioButtonEval; private System. windows. forms. radioButton radioButtonRun; private System. windows. forms. textBox textBoxMethodName; private System. componentModel. container components = null; public Form1 () {InitializeComponent (); this. comboBoxScript. selectedIndex = 0; this. scriptEngine = new ScriptEngine (); this. scriptEngine. useSafeSubset = true; this. scriptEngine. runError + = new RunErrorHandler (scriptEngine_RunError); this. scriptEngine. runTimeout + = new RunTimeoutHandler (scrip TEngine_RunTimeout);} protected override void Dispose (bool disposing) {if (disposing) if (components! = Null) components. dispose (); base. dispose (disposing);} # private void InitializeComponent () {// omitted} # endregion [STAThread] static void Main () {Application. run (new Form1 ();} // Run the script private void buttonRun_Click (object sender, System. eventArgs e) {this. scriptEngine. reset (); this. scriptEngine. language = (ScriptLanguage) Enum. parse (typeof (ScriptLanguage), this. comboBoxScr Ipt. selectedItem. toString (); this. scriptEngine. timeout = (int) this. numericUpDownTimeout. value; this. scriptEngine. allowUI = this. checkBoxAllowUI. checked; if (this. radioButtonEval. checked) // run the Eval method {this. textBoxResult. text = this. scriptEngine. eval (this. textBoxMethodName. text + "(" + this. textBoxParams. text + ")", this. textBoxCodeBody. text ). toString ();} else // Run the Run method {string [] parameters = (string []) thi S. textBoxParams. text. split (','); object [] paramArray = new object [parameters. length]; for (int I = 0; I <parameters. length; I ++) paramArray [I] = Int32.Parse (parameters [I]); this. textBoxResult. text = this. scriptEngine. run (this. textBoxMethodName. text, paramArray, this. textBoxCodeBody. text ). toString () ;}}// exit the program private void buttonCancel_Click (object sender, System. eventArgs e) {this. close ();} // error function p Rivate void scriptEngine_RunError () {MessageBox. Show ("RunError script execution error! ");} Private void scriptEngine_RunTimeout () {MessageBox. Show (" RunTimeout: The execution script times out, causing an error! ") ;}}} Wrote a JavaScript function in the text box. Input 12 and output 12000012. If the timeout time is adjusted to 1 ms, executing the script will jump out of the following timeout reminder box and trigger the event.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.