Kill Process By Name visual basic

Posted on 2004-09-15
Last Modified: 2010-05-18

I need a working module that kills procs by name.  I've found several but none seem to actually terminate the process.
Question by:bluedragon99
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +2
LVL 22

Expert Comment

ID: 12071698
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?
LVL 52

Expert Comment

by:Ryan Chong
ID: 12071902
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

Author Comment

ID: 12077353
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.
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI


Expert Comment

ID: 12077382

    Take a look here, this may cover you.


Author Comment

ID: 12077414
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..

Expert Comment

ID: 12077422

    Take a look here, this may cover you too.

LVL 22

Expert Comment

ID: 12077806
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.

Author Comment

ID: 12081198
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?

Expert Comment

ID: 12083697
    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.


Author Comment

ID: 12084437
Ok, I have tested it and it doesn't seem to work at all.....Doesn't anyone have something that is tested and works?
LVL 22

Accepted Solution

cookre earned 500 total points
ID: 12085892
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.


Author Comment

ID: 12085942
As usual...

You are a genius :)
LVL 10

Expert Comment

ID: 12284158
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

Featured Post

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

622 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question