简体   繁体   English

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

[英]How do I check if a certain process has focus?

I'm trying to check if javaw.exe has focus, then execute certain code if it does.我正在尝试检查 javaw.exe 是否具有焦点,如果是,则执行某些代码。

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

Is there any way to do this?有没有办法做到这一点?

You can determine this quite easily using the GetForegroundWindow() and GetWindowThreadProcessId() WinAPI functions.您可以使用GetForegroundWindow()GetWindowThreadProcessId() WinAPI 函数轻松确定这一点。

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.首先调用GetForegroundWindow获取当前聚焦窗口的窗口句柄,然后调用GetWindowThreadProcessId以检索该窗口的进程 ID。 Finally get it as a Process class instance by calling Process.GetProcessById()最后通过调用Process.GetProcessById()将其作为Process实例

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!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM