如何結束 Shell 所啟動的程式?
在 Shell & Wait 的程式怎麼寫?中, 我們說明了「如何等待 Shell 所啟動的程式」, 但如果被 Shell 所啟動的程式還沒有結束, 我們就想主動結束它, 該怎麼做呢?
此時應呼叫的 Windows API 是 TerminateProcess, 細節如下:
1. API 的宣告:
Const SYNCHRONIZE = &H100000
Const INFINITE = &HFFFFFFFF
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
Private Declare Function TerminateProcess Lib
"kernel32" Alias "TerminateProcess" (ByVal hProcess As Long, ByVal
uExitCode As Long) As Long
註:如果以上的宣告放在「一般模組」底下, 應將 Declare 之前的 Private 保留字去掉, 並且在 Const 之前加上 Public 保留字。
2. Shell 的程式範例:(以執行 MS-DOS 為例)
Dim pId As Long, pHnd As Long ' 分別宣告 Process Id 及 Process Handle 變數 pId = Shell("Command.com", vbNormalFocus) ' Shell 傳回 Process Id pHnd = OpenProcess(SYNCHRONIZE, 0, pId) ' 取得 Process Handle ... Call TerminateProcess( pHnd, 0 ) ' TerminateProcess 所傳入的是 Process Handle Call CloseHandle( pHnd )
但以上的方案只適用於 Shell 所啟動的程式, ShellExecute 則不適用, 原因是 ShellExecute 函數是透過檔案總管來啟動程式, 而檔案總管啟動程式之後, 並沒有將 Process ID 或 Process Handle 傳回來。