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

C# 發現之旅第十四講:VB.NET 腳本引擎(下)─ 執行腳本、演示代碼與部署總結

     編輯:關於C語言

執行腳本選單事件處理


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 執行。

演示腳本代碼 (demo.vbs)


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# 代碼直接複製至專案
  • 或
  • 修改專案屬性編譯為獨立 DLL,供其他 .NET 專案引用

部署極度輕量,零設定檔依賴。

小結

本課程以動態編譯技術實作 VB.NET 腳本引擎,提供類似 Office/VS.NET 的 VBA 擴充能力,大幅提升應用系統彈性。腳本引擎技術實用性強,值得推廣應用。

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