Minying's Blog

Just another WordPress.com weblog

Process 使用筆記

Posted by minying 於 23 四月, 2009

最近剛好有一個 CASE 需要用 VB.NET 去呼叫執行其他的應用程式,所以花了一些時間了解一下 Process 這個類別的使用。在此記錄一下,方便以後資料的查詢。如果大家有不錯的用法,也歡迎提供分享 ^_^ 。

呼叫 Process 方法,使用 Start 來啟動系上的處理序,在 Start 之前須先指定處理序檔名,方式是將 FileName 屬性設定處理序的完整路徑,而限定 Windows 應用程式的情形下,只需設定該處理序名稱即可。

  • 傳遞 FileName 參數以在執行階段啟動處理程序
Dim myProcess As Process = Process.Start("Notepad.exe")
  • 若要在執行階段使用 StartInfo 屬性來啟動處理程序

Dim myProcess As New Process()

myProcess.StartInfo.FileName = “Notepad.exe"

myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized ‘WindowStyle可以設定開啟視窗的大小

myProcess.Start()

  • 若要停止處理序,若處理序是無視窗,則呼叫 Kill 方法,但不會提示要儲存已變更的資料。任何未儲存的資料都將遺失。

Dim myProcesses() As Process
Dim myProcess As Process
‘ 回傳處理序名稱為 “Notepad" 的陣列
myProcesses = Process.GetProcessesByName(“Notepad")
For Each myProcess In myProcesses
    myProcess.CloseMainWindow()
Next

  • 判別處理序是否有回應,若沒有回應則強制關閉處理序。

Dim myProcesses() As Process
myProcesses = Process.GetProcessesByName(“Notepad.exe")
‘ Tests the Responding property for a True return value.
If myProcesses(0).Responding Then
    myProcesses(0).CloseMainWindow()
Else
    ‘ Forces the process to close if the Responding value is False.
    myProcesses(0).Kill()
End If

  • 判別處理序是否已經結束
If Not notepad.HasExited Then
    ' If the process is still running, close it.
    notepad.CloseMainWindow()
End If

等候處理序完成動作,若處理序會耗費一段時間,可以使用 WaitForInputIdle()
Dim myProcess As New Process()
myProcess = Process.Start("Notepad.exe")
myProcess.WaitForInputIdle()    '等候處理序完成再執行下面的動作
myProcess.WaitForExit(3000)     '等待3秒後,再執行下面的動作
myProcess.CloseMainWindow()

範例:
'宣告 myProcess 變數
Dim myProcess As System.Diagnostics.Process = New System.Diagnostics.Process

'設定顯示視窗大小
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
'指定 FileName 可指定執行檔或系統中已有設定關連的檔案,若已有安裝Office軟體,可指定Word文字檔,會自動開啟相關程式。
myProcess.StartInfo.FileName = "cmd.exe"
myProcess.StartInfo.FileName = "C:\TEMP\TEST.doc"

'啟動處理序
myProcess.Start()
'若要DOS視窗下送出命令 SendKey ,不知什麼原因(可能來不及反應)連續送出命令會沒有反應,所以加了等待時間,再送下一個命令。
SendKeys.Send("cd\") 或 SendKeys.Send("ping www.yahoo.com.tw")
myProcess.WaitForExit(1000)
SendKeys.Send("{Enter}")

'關閉處理序,詳細的說明,可參考前一篇文章。
myProcess.CloseMainWindow()

如果有個 Message.log 檔,希望由 Notepad 來開啟。
myProcess.StartInfo.FileName = "Notepad.exe"
myProcess.StartInfo.Arguments = "c:\Message.log"
myProcess.Start()

若是程序後需要帶參數也可以使用這種方式,沒有畫面的處理序很適用。相當於DOS下命令 C:\>tranzip.exe T1.txt T2.txt
myProcess.StartInfo.FileName = "tranzip.exe"
myProcess.StartInfo.Arguments = "T1.txt T2.txt"

開啟 IE 的方式
myProcess.StartInfo.FileName = "IExplore.exe"
myProcess.StartInfo.Arguments = www.google.com.tw
直接列印PDF檔案
myProcess.StartInfo.CreateNoWindow = true
myProcess.StartInfo.FileName = "c:\DKTD.pdf"
myProcess.StartInfo.Verb = "Print"

發表留言