# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB - End a process by its window title...

## sciguyryan

A lot of people have been asking for a code that will kill a process - here is something that I have some up with:


VB Code:
Private Const WM_CLOSE = &H10
Private g_TheCollWin As Collection
 Private Declare Function EnumWindows Lib "user32.dll" ( _
    ByVal lpEnumFunc As Long, _
    ByVal lParam As Long) As Boolean
Private Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" ( _
    ByVal hwnd As Long, _
    ByVal lpString As String, _
    ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "user32.dll" Alias "GetWindowTextLengthA" ( _
    ByVal hwnd As Long) As Long
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" ( _
    ByVal hwnd As Long, _
    ByVal wMsg As Long, _
    ByVal wParam As Long, _
    lParam As Any) As Long
Private Declare Function SetForegroundWindow Lib "user32.dll" ( _
    ByVal hwnd As Long) As Long
 Private Sub Kill_Process(ByVal strWindowTitle As String)
    Set g_TheCollWin = New Collection
    g_TheCollWin.Add strWindowTitle
    Call EnumWindows(AddressOf EnumWindowsProc, ByVal 0&)
End Sub
 Public Function EnumWindowsProc(ByVal lngHwnd As Long, ByVal lngParam As Long) As Boolean
    Dim strSave As String
    Dim lngRet As Long
    Dim varTheItem As Variant
    lngRet = GetWindowTextLength(lngHwnd)
    If lngRet > 0 Then
        strSave = Space$(lngRet)
        Call GetWindowText(lngHwnd, strSave, lngRet + 1)
        For Each varTheItem In g_TheCollWin
            If InStr(1, strSave, varTheItem, vbTextCompare) > 0 Then
                Call SetForegroundWindow(lngHwnd)
                Call SendMessage(lngHwnd, WM_CLOSE, 0, 0)
            End If
        Next
    End If
    EnumWindowsProc = True
End Function

This basically searches through the windows (Using the Collection Object) and then when it finds one with the given title it sends the close mesaage to it, making it to close.

The call function is simple:


VB Code:
Kill_Process ("ApiViewer 2004 [Win32api.apv]")

In the example above, if the API Viewer is open then it will kill it. This string can be a partial or a full string.

*One Note:* this *Will not* work on processes that do not have windows.

Cheers and hoep that helps someone  :Smilie: 

Cheers,

RyanJ

----------


## |2eM!x

another way...


VB Code:
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As Long) As Long
Declare Function sendmessagebystring Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Declare Function getwindow Lib "user32" Alias "GetWindow" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
    Public Const WM_CLOSE = &H10
    Public Const GW_CHILD = 5
    Public Const GW_HWNDFIRST = 0
    Public Const GW_HWNDLAST = 1
    Public Const GW_HWNDNEXT = 2
    Public Const GW_HWNDPREV = 3
    Public Const GW_MAX = 5
    Public Const GW_OWNER = 4
'**************************************
' Name: Close a window(if you know part
'     of the title)
' Description:This code closes a window,
'     if you know part of it's title. It uses
'     some AOL API's, hehe(sendmessagebystring
'     ). I used it for closing Netscape window
'     s because the "Window Class Name" always
'     changed. Not sure if this code has any u
'     se though...
' By: Che
'
' Assumes:1. The title, or part of the t
'     itle.
'2. A form named "Form1", or you could change the code a little
'
'This code is copyrighted and has' limited warranties.Please see [url]http://w[/url]
'     ww.Planet-Source-Code.com/vb/scripts/Sho
'     wCode.asp?txtCodeId=5499&lngWId=1'for details.'**************************************
   Function FindWindowByTitle(Title As String)
    Dim a, b, Caption
    a = getwindow(frmMain.hwnd, GW_OWNER)
    Caption = GetCaption(a)
      If InStr(1, LCase(Caption), LCase(Title)) <> 0 Then
        FindWindowByTitle = b
        Exit Function
    End If
    b = a
      Do While b <> 0: DoEvents
        b = getwindow(b, GW_HWNDNEXT)
        Caption = GetCaption(b)
          If InStr(1, LCase(Caption), LCase(Title)) <> 0 Then
            FindWindowByTitle = b
            Exit Do
            Exit Function
        End If
    Loop
End Function
  Function GetCaption(hwnd)
    Dim hwndLength%, hwndTitle$, a%
    hwndLength% = GetWindowTextLength(hwnd)
    hwndTitle$ = String$(hwndLength%, 0)
    a% = GetWindowText(hwnd, hwndTitle$, (hwndLength% + 1))
    GetCaption = hwndTitle$
End Function
  Sub KillWin(Title As String)
    Dim a, hwnd
    hwnd = FindWindowByTitle(Title)
    a = sendmessagebystring(hwnd, WM_CLOSE, 0, 0)
End Sub

KillWin ("Diablo II")

----------


## sciguyryan

Another interesting way, thank you for sharing that with us |2eM!x  :Smilie: 

Cheers,

RyanJ

----------


## |2eM!x

jup jup!

----------


## Sir Loin

Yet another way, I find this the easiest...


VB Code:
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const WM_CLOSE = &H10
 Private Sub Form_Load()
    Dim WindowName As String
     Dim Window As Long
    
        WindowName = InputBox("What window do you want to close?", "What Window")
         Window = FindWindow(vbNullString, WindowName)
    
        SendMessage Window, WM_CLOSE, 0, vbNullString
    
        Unload Me
End Sub

-Sir Loin

----------


## sciguyryan

That is exactly the same method as mine uses if you noticed  :Wink: 

All the difference and extra code allows for multiple windows to be closed  :Smilie: 

Cheers,

RyanJ

----------


## Sir Loin

Oops, now that I look at that, you're right. 
Sorry, when I posted that I was tired...

-Sir Loin

----------


## sciguyryan

> Oops, now that I look at that, you're right. 
> Sorry, when I posted that I was tired...
> 
> -Sir Loin


Its fine, it saves all of the code we have posted if you only need to close a single window  :Smilie: 


Cheers,

RyanJ

----------


## kpmsivachand

Can anyone tell me how to terminate the process with using the pid?

----------


## manavo11

Look for the TerminateProcess API.

http://www.vbforums.com/showthread.p...rminateProcess

----------


## kpmsivachand

Thank for the link... Let me check out now

----------


## allawnh

'This is probably the easiest of all. 


'Step 1: make sure to create one button called "Command1" on a new form
'Step 2: create a text file and type: "taskkill /IM excel.exe /F" into it
'Note: /F forcefully terminates the process. Leave it out if you would like to gracefully shut it down. This means that if the file must be saved due to changes windows will ask you first.
'Step3: Name the text file "killprocess" and save to C drive. (this is what I called it and where I saved it in this code)
'Step4: Change the extention of the text file to ".bat"
'Note: This is to end all instances of Excel that are running in the task manager. If it is another program you wish to terminate, then find out its process name from the task manager.
'This works 100%. I have tested it.


Private Sub Command1_Click()
Shell "C:\killprocess.bat", vbHide
End Sub

----------


## kpmsivachand

The question was how to do with pid???? Please read the question fully and post reply

----------


## Edgemeal

> The question was how to do with pid???? Please read the question fully and post reply




```
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal handle As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long

Public Function KillProcess(ByVal ProcessID As Long) As Boolean
    Dim hProc As Long
    Const SYNCHRONIZE = &H100000
    Const PROCESS_TERMINATE As Long = &H1
    Const fdwAccess As Long = SYNCHRONIZE Or PROCESS_TERMINATE
    hProc = OpenProcess(fdwAccess, 0&, ProcessID)
    If hProc Then
        If TerminateProcess(hProc, 0&) Then KillProcess = True
        Call CloseHandle(hProc)
    End If
End Function
```

----------


## kpmsivachand

> ```
> Option Explicit
> Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
> Private Declare Function CloseHandle Lib "kernel32" (ByVal handle As Long) As Long
> Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
> 
> Public Function KillProcess(ByVal ProcessID As Long) As Boolean
>     Dim hProc As Long
>     Const SYNCHRONIZE = &H100000
> ...


Thanks for the code...

----------


## CDRIVE

> ```
> Option Explicit
> Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
> Private Declare Function CloseHandle Lib "kernel32" (ByVal handle As Long) As Long
> Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
> 
> Public Function KillProcess(ByVal ProcessID As Long) As Boolean
>     Dim hProc As Long
>     Const SYNCHRONIZE = &H100000
> ...


Could you possibly expand on this. I need to return the PID of a particular instance of SvcHost. I want to kill it if it's using more than 80% of CPU cycles. Pointing me in the right direction would be of great help.

Thanks

----------


## Bonnie West

> ... I need to return the PID of a particular instance of SvcHost. I want to kill it if it's using more than 80% of CPU cycles. Pointing me in the right direction would be of great help.


Process Explorer/Process Hacker can help you identify which service is taxing your CPU so you can stop it gracefully.

----------


## CDRIVE

> Process Explorer/Process Hacker can help you identify which service is taxing your CPU so you can stop it gracefully.


Thank You. I'll check them out.

----------

