我正在尝试检查javaw.exe是否具有焦点,然后执行某些代码。
以前我有代码可以查找javaw.exe的进程ID,然后将它与当前有焦点的进程进行比较,该进程工作了一段时间,但后来我注意到我运行了多个javaw.exe进程,它只适用于其中一个进程,而当任何javaw.exe进程具有焦点时我需要它才能工作。
有没有办法做到这一点?
答案 0 :(得分:1)
您可以使用GetForegroundWindow()
和GetWindowThreadProcessId()
WinAPI函数轻松确定这一点。
首先调用GetForegroundWindow
以获取当前焦点窗口的窗口句柄,然后调用GetWindowThreadProcessId
以检索该窗口的进程ID。最后通过调用Process
class
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
希望这有帮助!