CodeItBetter Programming Another VB Programming Blog

How to terminate an application

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'System & API - How to terminate an application
Option Explicit
 
'Declarations and constants to Terminate process
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, _
    ByRef lpdwProcessId As Long) As Long
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 TerminateProcess Lib "Kernel32" (ByVal hProcess As Long, _
    ByVal uExitCode As Long) As Long
Private Const SYNCHRONIZE = &H100000
Private Const PROCESS_TERMINATE As Long = &H1
 
'API Declarations to Find Parent and Child windows
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long
 
Public Function fnTerminateProcess(ByVal WindowClassName As String)
    'This Procedure will terminate the process.
    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(WindowClassName, vbNullString)
    If target_hwnd = 0 Then
        Debug.Print "Error finding target window handle"
        Exit Function
    End If
 
    ' Get the process ID.
    GetWindowThreadProcessId target_hwnd, target_process_id
    If target_process_id = 0 Then
        Debug.Print "Error finding target process ID"
        Exit Function
    End If
 
    ' Open the process.
    target_process_handle = OpenProcess(SYNCHRONIZE Or PROCESS_TERMINATE, ByVal 0&, _
        target_process_id)
    If target_process_handle = 0 Then
        Debug.Print "Error finding target process handle"
        Exit Function
    End If
 
    ' Terminate the process.
    If TerminateProcess(target_process_handle, 0&) = 0 Then
        Debug.Print "Error terminating process"
    Else
        Debug.Print "terminated"
    End If
 
    ' Close the process.
    CloseHandle target_process_handle
End Function
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.