Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleKill another application given its name
Description
Keywordskill, stop, halt, end, SendMessage
CategoriesAPI, Software Engineering
 
Use the EnumWindows API function to examine each running window. Use GetWindowText to determine each window's title. When it finds the target window, the programn uses SendMessage to make the target close itself.
 
Private Target As String

' Ask Windows for the list of tasks.
Public Sub TerminateTask(app_name As String)
    Target = app_name
    EnumWindows AddressOf EnumCallback, 0
End Sub

' Check a returned task to see if we should
' kill it.
Public Function EnumCallback(ByVal app_hWnd As Long, ByVal _
    param As Long) As Long
Dim buf As String * 256
Dim title As String
Dim length As Long

    ' Get the window's title.
    length = GetWindowText(app_hWnd, buf, Len(buf))
    title = Left$(buf, length)

    ' See if this is the target window.
    If InStr(title, Target) <> 0 Then
        ' Kill the window.
        SendMessage app_hWnd, WM_CLOSE, 0, 0
    End If

    ' Continue searching.
    EnumCallback = 1
End Function
 
Note: Esben Maal discovered that this did not work on his system, but it works when he uses PostMessage instead of SendMessage.
 
Declare Function PostMessage Lib "user32" Alias _
    "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _
    ByVal wParam As Long, ByVal lParam As Long) As Long
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated