|
|
Title | Terminate a process immediately |
Description | This example shows how to terminate a process immediately in Visual Basic 6. |
Keywords | terminate, end, halt, stop, kill |
Categories | Software Engineering, API |
|
|
This example's download contains two projects. The Target project is a simple application that catches its QueryUnload event and refuses to unload unless it's the program's own idea. In particular, it does not close if you send it the WM_CLOSE message.
|
|
Private m_OkToClose As Boolean
Private Sub cmdClose_Click()
m_OkToClose = True
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode _
As Integer)
Cancel = Not m_OkToClose
If Cancel Then MsgBox "Unload ignored"
End Sub
|
|
The second project is the Terminator. If you click the Close button, the program uses the FindWindow API function to find the target application and sends it the WM_CLOSE message. A normal program should clean up and stop when it receives this message but the Target program continues.
|
|
Private Sub cmdSendCloseMessage_Click()
Dim target_hwnd As Long
' Get the target's window handle.
target_hwnd = FindWindow(vbNullString, _
txtTargetTitle.Text)
If target_hwnd = 0 Then
MsgBox "Error finding target window handle"
Exit Sub
End If
' Send the application the WM_CLOSE message.
PostMessage target_hwnd, WM_CLOSE, 0, 0
MsgBox "Sent WM_CLOSE message"
End Sub
|
|
If you click the Terminate button, the gloves come off. The program uses FindWindow to find the target's window handle. It uses GetWindowThreadProcessId to get the window'sprocess ID, and then uses OpenProcess to open a connection to the process. It then calls TerminateProcess to force the target to stop immediately (no saving throw).
|
|
' Terminate the process.
Private Sub cmdTerminate_Click()
Dim target_hwnd As Long
Dim target_process_id As Long
Dim target_process_handle As Long
' Get the target's window handle.
target_hwnd = FindWindow(vbNullString, _
txtTargetTitle.Text)
If target_hwnd = 0 Then
MsgBox "Error finding target window handle"
Exit Sub
End If
' Get the process ID.
GetWindowThreadProcessId target_hwnd, target_process_id
If target_process_id = 0 Then
MsgBox "Error finding target process ID"
Exit Sub
End If
' Open the process.
target_process_handle = OpenProcess( _
SYNCHRONIZE Or PROCESS_TERMINATE, _
ByVal 0&, target_process_id)
If target_process_handle = 0 Then
MsgBox "Error finding target process handle"
Exit Sub
End If
' Terminate the process.
If TerminateProcess(target_process_handle, 0&) = 0 Then
MsgBox "Error terminating process"
Else
MsgBox "Process terminated"
End If
' Close the process.
CloseHandle target_process_handle
End Sub
|
|
|
|
|
|