1

I have a query, how can I kill a process with just the class name using FindWindowEx

enter image description here

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
Angel WT
  • 11
  • 1

1 Answers1

1

If you have been able to reliably get a window handle back from calling FindWindowEx you can then use GetWindowThreadProcessId to find the ID of the process from the window handle.

Once you have the process ID you can find the Process by that ID and call Kill() on it. For example:

Imports System.Runtime.InteropServices
Imports System.Diagnostics

Module Module1

    <DllImport("user32.dll", SetLastError:=True)>
    Private Function GetWindowThreadProcessId(ByVal hwnd As IntPtr,
                          ByRef lpdwProcessId As Integer) As Integer
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Function FindWindowEx(ByVal parentHandle As IntPtr,
                      ByVal childAfter As IntPtr,
                      ByVal lclassName As String,
                      ByVal windowTitle As String) As IntPtr
    End Function

    Sub Main()

        Dim hWnd As IntPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_0", "Spotify Premium")
        Dim ProcessId As Integer
        GetWindowThreadProcessId(hWnd, ProcessId)

        If ProcessId <> 0 Then
            Dim Process As Process = Process.GetProcessById(ProcessId)
            Process.Kill()
        End If


    End Sub

End Module

The tricky part will be making sure that you can always get a window handle. Think about cases when there are multiple instances of the handle. You mention class name but it will likely also be necessary to supply the window title to FindWindowEx.

You may also need to consider what happens if calling Process.Kill() should throw an exception, for example, if the user that your program is running under doesn't have the rights to kill that particular process.

Steve Springer
  • 206
  • 2
  • 4