Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Kill Process By Name visual basic

Posted on 2004-09-15
13
Medium Priority
?
5,870 Views
Last Modified: 2010-05-18
Hello,

I need a working module that kills procs by name.  I've found several but none seem to actually terminate the process.
0
Comment
Question by:bluedragon99
[X]
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
13 Comments
 
LVL 22

Expert Comment

by:cookre
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?
0
 
LVL 53

Expert Comment

by:Ryan Chong
ID: 12071902
Try see this on how to retrieve and kill the processes that are running:
http://www.freevbcode.com/ShowCode.ASP?ID=5543

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&
   Else
      MsgBox "My Exe is not open."
   End If
End Sub
0
 
LVL 1

Author Comment

by:bluedragon99
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.
0
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
LVL 9

Expert Comment

by:Dang123
ID: 12077382
bluedragon99,

    Take a look here, this may cover you.

http://www.vbusers.com/code/codeget.asp?ThreadID=200&PostID=1&NumReplies=0

Dang123
0
 
LVL 1

Author Comment

by:bluedragon99
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..
0
 
LVL 9

Expert Comment

by:Dang123
ID: 12077422
bluedragon99,

    Take a look here, this may cover you too.

http://www.andreavb.com/tip020021.html

Dang123
0
 
LVL 22

Expert Comment

by:cookre
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.
0
 
LVL 1

Author Comment

by:bluedragon99
ID: 12081198
Ok this looks like what I need maybe http://www.andreavb.com/tip020021.html

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?
0
 
LVL 9

Expert Comment

by:Dang123
ID: 12083697
bluedragon99,
    I beleave the code takes an exe name. Run a version modified like this

Private Sub Form_Load()
    Const PROCESS_ALL_ACCESS = 0
    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)
   
    Do
        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.

Dang123
0
 
LVL 1

Author Comment

by:bluedragon99
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?
0
 
LVL 22

Accepted Solution

by:
cookre earned 2000 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)

Why?
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.

0
 
LVL 1

Author Comment

by:bluedragon99
ID: 12085942
As usual...

You are a genius :)
0
 
LVL 10

Expert Comment

by:jagadeesh_motamarri
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
Const GW_HWNDNEXT = 2
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)
    Loop
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
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

In this post we will learn different types of Android Layout and some basics of an Android App.
The SignAloud Glove is capable of translating American Sign Language signs into text and audio.
Introduction to Processes
Starting up a Project

661 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