Sunday, June 17, 2012

Menutup Sebuah Aplikasi Secara Paksa (Force Terminate)

Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
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

Public Sub terminateApp(ByVal sWindowTitle As String, ByVal fSilent As Boolean)


Dim lHwnd As Long
Dim lProc As Long
Dim lProcHnd As Long

On Error GoTo ErrHandler

sWindowTitle = "Inbox - Thunderbird"
sWindowTitle = "Test"

lHwnd = FindWindow(vbNullString, sWindowTitle)
If lHwnd = 0 Then
If fSilent Then
Exit Sub
Else
Err.Raise 1, , "Can"
End If
End If

GetWindowThreadProcessId lHwnd, lProc
If lProc = 0 Then
If fSilent Then
Exit Sub
Else
Err.Raise 1, , "Can"
End If
End If

lProcHnd = OpenProcess(SYNCHRONIZE Or PROCESS_TERMINATE, 0, lProc)
If lProcHnd = 0 Then
If fSilent Then
Exit Sub
Else
Err.Raise 1, , "Can"
End If
End If

If TerminateProcess(lProcHnd, 0&) <> 0 Then
If Not fSilent Then
Err.Raise 1, , "Failed to terminate process"
End If
End If

CloseHandle lProcHnd

Exit Sub

ErrHandler:

Err.Raise Err.Number, , Err.Description

End Sub