Kill Process By Name visual basic


I need a working module that kills procs by name.  I've found several but none seem to actually terminate the process.
Who is Participating?
You didn't say how it failed, but I suspect it got an ACCESS_DENIED on the OpenProcess().

If you display err.LastDllError, e.g.:   MsgBox(Str(err.LastDllError))
I bet you'll get a 5 (access denied)

The permissions requested on the OpenProcess() were - NONE.

Change  Const PROCESS_ALL_ACCESS = 0
to          Const PROCESS_ALL_ACCESS = 4095

and I bet it'll work better - assuming you run it under an account that grant itself full privileges.

Processes don't have names per se, just numeric identifiers.  What you see in TaskManager is the name of the executing module, and there may be many processes running off the same module.

Also, each process requires a certain permission level to kill it.

Can you post a link to one of the examples that fails, how you used it, and how it failed?
Ryan ChongCommented:
Try see this on how to retrieve and kill the processes that are running:

If you want to kill the process by window's caption, try like:

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Const WM_CLOSE = &H10

Private Sub Form_Load()
   Dim winHwnd As Long
   Dim RetVal As Long
   winHwnd = FindWindow(vbNullString, "My Window's Caption")
   If winHwnd <> 0 Then
      PostMessage winHwnd, WM_CLOSE, 0&, 0&
      MsgBox "My Exe is not open."
   End If
End Sub
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

bluedragon99Author Commented:
Thanks, but I need to kill it by process name.  Does anybody have a time tested module that works?  All that I have tried from EE run but do not kill the process at all.

    Take a look here, this may cover you.

bluedragon99Author Commented:
Hehe thats what I'm trying to replace in my code, it's going to be distrubuted retail wise and I don't want to have to include kill.exe in the package..

    Take a look here, this may cover you too.

You'll note that all of them are based on the name of the executing module, since processes don't have their own names.

The first one (that uses kill.exe) at least just kills just one instance of the named executable, although you can't be sure of which.  

The last one will kill all instances.  I do note that the last one uses API calls only from kernel32, and those calls are supported on all versions of Windows from 95 on.

Just remember - processes don't have unique text names - just numeric identifiers.  The associated executable module name is fine as an identifier if you know there will never be multiple instrances, or if you don't mind killing all instances.

Several final observations:

1) TerminateProcess() (the API call used to do the actual termination) is not neccesarily clean - it can leave some loaded DLLs in an indeterminate state.   If practcal, send a WM_CLOSE first, and use TerminateProcess() only as a last resort.

2) TerminmateProcess() is just a request - control returns immediately.  Hence, if you need to know that the process has terminated, you have to do an extra check.

3) TerminateProcess() is not omnipotent - some hung I/O states can inhibit the target process from terminating.

4) The procees handle you pass to TerminateProcess() requires PROCESS_TERMINATE permission.  Not all of your users may have that right unless the target process owner is at their permission level.
bluedragon99Author Commented:
Ok this looks like what I need maybe

I need to kill all instances ex 4 calc.exe's open all need to be killed..

don't have the means to test it now but that code will take a module name?
    I beleave the code takes an exe name. Run a version modified like this

Private Sub Form_Load()
    Const TH32CS_SNAPPROCESS As Long = 2&
    Dim uProcess  As PROCESSENTRY32
    Dim RProcessFound As Long
    Dim hSnapshot As Long
    Dim SzExename As String
    Dim ExitCode As Long
    Dim MyProcess As Long
    Dim AppKill As Boolean
    Dim AppCount As Integer
    Dim i As Integer
    Dim WinDirEnv As String
    uProcess.dwSize = Len(uProcess)
    hSnapshot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    RProcessFound = ProcessFirst(hSnapshot, uProcess)
        i = InStr(1, uProcess.szexeFile, Chr(0))
        SzExename = LCase$(Left$(uProcess.szexeFile, i - 1))
        WinDirEnv = Environ("Windir") + "\"
        WinDirEnv = LCase$(WinDirEnv)
        MsgBox SzExename
        RProcessFound = ProcessNext(hSnapshot, uProcess)
    Loop While RProcessFound
    Call CloseHandle(hSnapshot)
End Sub

  with the API defined as in the link to see for yourself.

bluedragon99Author Commented:
Ok, I have tested it and it doesn't seem to work at all.....Doesn't anyone have something that is tested and works?
bluedragon99Author Commented:
As usual...

You are a genius :)
TerminateProcess API call should sove ur problem

just have glance at the following code.......

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SetParent Lib "user32" (ByVal hWndChild As Long, ByVal hWndNewParent As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long
Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Declare Function DestroyWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function Putfocus Lib "user32" Alias "SetFocus" (ByVal hwnd As Long) As Long
Dim mWnd As Long
Function InstanceToWnd(ByVal target_pid As Long) As Long
    Dim test_hwnd As Long, test_pid As Long, test_thread_id As Long
    'Find the first window
    test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
    Do While test_hwnd <> 0
        'Check if the window isn't a child
        If GetParent(test_hwnd) = 0 Then
            'Get the window's thread
            test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)
            If test_pid = target_pid Then
                InstanceToWnd = test_hwnd
                Exit Do
            End If
        End If
        'retrieve the next window
        test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
End Function
Private Sub Form_Load()
    Dim Pid As Long
    'Lock the window update
    LockWindowUpdate GetDesktopWindow
    'Execute notepad.Exe
    Pid = Shell("c:\windows\notepad.exe", vbNormalFocus)
    If Pid = 0 Then MsgBox "Error starting the app"
    'retrieve the handle of the window
    mWnd = InstanceToWnd(Pid)
    'Set the notepad's parent
    SetParent mWnd, Me.hwnd
    'Put the focus on notepad
    Putfocus mWnd
    'Unlock windowupdate
    LockWindowUpdate False
End Sub
Private Sub Form_Unload(Cancel As Integer)
    'Unload notepad
    DestroyWindow mWnd
    'End this program
    TerminateProcess GetCurrentProcess, 0
End Sub
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.