首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 發現之旅第十四講:VB.NET 腳本引擎(下)─ 全域物件容器與腳本引擎初始化

     編輯:關於C語言

GlobalObject 全域物件容器


namespace MyVBAScript.Global {
    [StandardModuleAttribute()]
    public class GlobalObject {
        internal static XVBAWindowObject myWindow = null;
        public static XVBAWindowObject Window => myWindow;

        internal static frmMain.DocumentClass myDocument = null;
        public static frmMain.DocumentClass Document => myDocument;
    }
}
  • StandardModuleAttribute 使成員成為全域可見
  • 獨立命名空間 MyVBAScript.Global 減少編譯器掃描負擔
  • 靜態屬性 Window/Document 供腳本直接存取

腳本引擎初始化 (frmMain_Load)


private void frmMain_Load(object sender, EventArgs e) {
    myVBAEngine = new XVBAEngine();
    myVBAEngine.AddReferenceAssemblyByType(this.GetType());
    myVBAEngine.VBCompilerImports.Add("MyVBAScript.Global");

    MyVBAScript.Global.GlobalObject.myWindow = new XVBAWindowObject(this, myVBAEngine, this.Text);
    MyVBAScript.Global.GlobalObject.myDocument = new DocumentClass(this);

    string demoPath = Path.Combine(Application.StartupPath, "demo.vbs");
    if (File.Exists(demoPath)) {
        string script = File.ReadAllText(demoPath, Encoding.GetEncoding("gb2312"));
        myVBAEngine.ScriptText = script;
        if (!myVBAEngine.Compile())
            txtEditor.Text = "編譯預設腳本錯誤:\r\n" + myVBAEngine.CompilerOutput;
        RefreshScriptMethodList();
    }
}

RefreshScriptMethodList 重整選單


private void RefreshScriptMethodList() {
    btnRunScript.DropDownItems.Clear();
    string[] names = myVBAEngine.ScriptMethodNames;
    if (names != null && names.Length > 0) {
        foreach (string name in names) {
            ToolStripMenuItem item = new ToolStripMenuItem();
            item.Text = name;
            item.Click += ScriptItem_Click;
            btnRunScript.DropDownItems.Add(item);
        }
        myStatusLabel.Text = "共載入 " + names.Length + " 個腳本方法";
    } else {
        ToolStripMenuItem item = new ToolStripMenuItem();
        item.Enabled = false;
        item.Text = "沒有載入任何腳本方法";
        btnRunScript.DropDownItems.Add(item);
        myStatusLabel.Text = "沒有載入任何腳本方法";
    }
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved