如何呼叫外部執行檔並等待其結束

如何呼叫外部執行檔並等待其結束

如何用 VB 或 VB.Net 呼叫外部執行檔 , 並等待其結束後再返回原本的程序

<< VB.Net 寫法 >>

Dim p As New Process
p.StartInfo.FileName = "C:\外部執行檔
.exe"
p.Start()
p.WaitForExit() ' 指示 Process 元件無限期等候相關處理序的結束。

================================================================

方法 1 :

' 建立 WScript.Shell 物件類別 , 並使用 Run 方法來呼叫執行檔

' 說明 : WshShell.Run (strCommand, [intWindowStype], [bWaitOnReturn])

CreateObject("WScript.Shell").Run "C:\外部執行檔.exe", 1, True

================================================================

方法 2 :

' Call API來做

Private Const SYNCHRONIZE = &H100000

Private Const INFINITE = &HFFFFFFFF

Private Const WAIT_TIMEOUT = &H102&

Private Declare Function OpenProcess Lib "kernel32" _

(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Declare Function WaitForSingleObject Lib "kernel32" _

(ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long

pId = Shell(外部執行檔) ' 用 Shell 函數執行外部 EXE , 並取得 ProcessID

pHnd = OpenProcess(SYNCHRONIZE, 0, pId) ' 開啟行程同步

If pHnd <> 0 Then

WaitForSingleObject pHnd, INFINITE ' 用WaitForSingleObject等待外部檔案執行完畢或結束關閉

CloseHandle pHnd

End If