private void ScriptItem_Click(object sender, EventArgs e) {
ToolStripMenuItem item = (ToolStripMenuItem)sender;
try {
myVBAEngine.Execute(item.Text, null, true);
} catch (Exception ex) {
Console.WriteLine("執行腳本 " + item.Text + " 錯誤:" + ex);
MessageBox.Show(this, "執行腳本 " + item.Text + " 錯誤:" + ex.Message);
}
}
選單項目文字即為腳本方法名稱,點選時呼叫 Execute 執行。
Sub 顯示當前使用的腳本代碼()
document.text = window.engine.ScriptText
End Sub
Sub 插入當前時間()
document.Selection = DateTime.Now.ToString("yyyy年MM月dd日HH:mm:ss")
End Sub
Sub 螢幕狀態()
window.alert("螢幕大小:" & window.ScreenWidth & " * " & window.ScreenHeight & vbCrLf _
& "視窗位置:" & window.Left & " " & window.Top & vbCrLf _
& "視窗大小:" & window.Width & " * " & window.Height)
End Sub
Sub ShowText()
window.alert(document.text)
End Sub
Sub MoveWindow()
window.Left = 100
End Sub
Sub ShowFileName()
window.alert("當前檔案名為:" & document.FileName)
End Sub
Sub AniMoveWindow()
window.Left = window.Left - 10
If window.Left > 10 Then window.SetTimeout(500, "AniMoveWindow")
End Sub
Dim Rate As Double
Sub 模擬顯示正弦曲線()
Rate = Rate + 0.1
If Rate > 50 Then Exit Sub
Dim strText As New String(" "c, 50 + CInt(Math.Sin(Rate) * 30))
document.AppendText(vbCrLf & strText & "######")
window.SetTimeout(100, "模擬顯示正弦曲線")
window.Title = Math.Sin(Rate)
End Sub
Dim strTitle As String = "《C#發現之旅》系列課程的VB.Net腳本演示 袁永福編寫 版權所有2008年"
Dim TitleCount As Integer
Sub 在標題欄顯示移動字幕()
TitleCount = TitleCount + 1
If TitleCount > strTitle.Length Then TitleCount = 0 : Exit Sub
window.Title = strTitle.Substring(strTitle.Length - TitleCount, TitleCount)
window.SetTimeOut(100, "在標題欄顯示移動字幕")
End Sub
Rate 計數,每 100ms 透過 SetTimeout 遞迴調用自身,利用 Math.Sin 計算空白長度模擬波形,50 次後停止SetTimeout 實現動畫效果,逐字顯示標題文字XVBAEngine 等 C# 代碼直接複製至專案部署極度輕量,零設定檔依賴。
本課程以動態編譯技術實作 VB.NET 腳本引擎,提供類似 Office/VS.NET 的 VBA 擴充能力,大幅提升應用系統彈性。腳本引擎技術實用性強,值得推廣應用。