3

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

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

有没有办法做到这一点?

4

1 回答 1

3

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

首先调用GetForegroundWindow以获取当前聚焦窗口的窗口句柄,然后调用GetWindowThreadProcessId以检索该窗口的进程 ID。最后通过调用将其作为Process实例获取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

希望这可以帮助!

于 2017-01-26T20:30:25.543 回答