# Re: 如何关闭叫出执行的程式

Posted by cww on March 15, 1998 at 21:32:05:

In Reply to: 如何关闭叫出执行的程式 posted by 赖皮 on March 12, 1998 at 08:55:31:

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 GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" _
(ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Const PROCESS_QUERY_INFORMATION = &H400
Const STILL_ALIVE = &H103
Const INFINITE = &HFFFF

Private ExitCode As Long
Private hProcess As Long
Private isDone As Long

Private Sub Command1_Click()
Dim pid As Long
pid = Shell("C:\tools\spe3\pe2.exe", vbNormalFocus)
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid)
isDone = False
Do
Call GetExitCodeProcess(hProcess, ExitCode)
Debug.Print ExitCode
DoEvents
Loop While ExitCode = STILL_ALIVE
Call CloseHandle(hProcess)
isDone = True
End Sub

Private Sub Command3_Click()
Dim aa As Long
If hProcess 0 Then
aa = TerminateProcess(hProcess, 3838)
End If

End Sub

执行了 TerminateProcess(hProcess, 3838)那会看到 command1_click()
的ExitCode = 3838。然
而，这个方式在win95没问题，在NT中，可能您要在OpenProcess()的第一个参数要
更改成 PROCESS_QUERY_INFORMATION Or PROCESS_TERMINATE 这样才能Work。不过
良心的建议，非到最后关头，不要使用TerminateProcess()，因不正常的结束，往
往许多程式结束前所要做的事都没有做，可能造成Resource的浪费，甚者，下次再
执行某些程式时会有问题

Follow Ups: