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 = "沒有載入任何腳本方法";
}
}
