Solved

Kill Process By Name visual basic

Posted on 2004-09-15
13
5,854 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
  • 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 49

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
 
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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 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)

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This is about my first experience with programming Arduino.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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 …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

706 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now