如何检查某个进程是否有焦点?

How do I check if a certain process has focus?

我正在尝试检查 javaw.exe 是否有焦点,如果有则执行特定代码。

以前我有代码会查找 javaw.exe 的进程 ID,然后将其与当前有焦点的进程进行比较,这工作了一段时间,但后来我注意到我有多个 javaw.exe 进程 运行,它只能在其中一个进程上工作,而我需要它在任何 javaw.exe 进程有焦点时工作。

有什么办法吗?

您可以使用 GetForegroundWindow() and GetWindowThreadProcessId() WinAPI 函数很容易地确定这一点。

首先调用GetForegroundWindow获取当前焦点window的window句柄,然后调用GetWindowThreadProcessId获取[=30]的进程ID =].最后得到它作为 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

用法举例:

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

希望对您有所帮助!