How do I check if a certain process has focus?

2019-09-20 16:44发布

I'm trying to check if javaw.exe has focus, then execute certain code if it does.

Previously I had code which would look for the process ID of javaw.exe, then compare it to the process which currently had focus, which worked for awhile, but then I noticed when I had more than one javaw.exe process running, it would only work on one of those processes, while I need it to work when any javaw.exe process has focus.

Is there any way to do this?

1条回答
神经病院院长
2楼-- · 2019-09-20 17:47

You can determine this quite easily using the GetForegroundWindow() and GetWindowThreadProcessId() WinAPI functions.

First call GetForegroundWindow to get the window handle of the currently focused window, then call GetWindowThreadProcessId in order to retrieve the process id of that window. Finally get it as a Process class instance by calling Process.GetProcessById()

Public NotInheritable Class ProcessHelper
    Private Sub New() 'Make no instances of this class.
    End Sub

    <DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetForegroundWindow() As IntPtr
    End Function

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

    Public Shared Function GetActiveProcess() As Process
        Dim FocusedWindow As IntPtr = GetForegroundWindow()
        If FocusedWindow = IntPtr.Zero Then Return Nothing

        Dim FocusedWindowProcessId As UInteger = 0
        GetWindowThreadProcessId(FocusedWindow, FocusedWindowProcessId)

        If FocusedWindowProcessId = 0 Then Return Nothing
        Return Process.GetProcessById(CType(FocusedWindowProcessId, Integer))
    End Function
End Class

Usage example:

Dim ActiveProcess As Process = ProcessHelper.GetActiveProcess()

If ActiveProcess IsNot Nothing AndAlso _
    String.Equals(ActiveProcess.ProcessName, "javaw", StringComparison.OrdinalIgnoreCase) Then
    MessageBox.Show("A 'javaw.exe' process has focus!")
End If

Hope this helps!

查看更多
登录 后发表回答