您可以使用Platform Invocation(简称P/Invoke)访问WinAPI函数GetForegroundWindow()和GetWindowThreadProcessId()。
您可以使用GetForegroundWindow() 来获取当前焦点/活动窗口的窗口句柄,然后调用GetWindowThreadProcessId() 来获取该窗口的进程ID。然后,您可以使用该 ID 获取 .NET Process class 的实例,您可以使用它轻松访问进程的名称等。
首先创建一个名为NativeMethods 的类。在这里,我们将声明所有 P/Invoked 函数:
Imports System.Runtime.InteropServices
Public NotInheritable Class NativeMethods
Private Sub New() 'Private constructor as we're not supposed to create instances of this class.
End Sub
<DllImport("user32.dll")> _
Public Shared Function GetForegroundWindow() As IntPtr
End Function
<DllImport("user32.dll")> _
Public Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, <Out()> ByRef lpdwProcessId As UInteger) As UInteger
End Function
End Class
然后您可以在代码中创建一个函数,使用这些函数来获取活动进程:
Public Function GetActiveProcess() As Process
Dim hWnd As IntPtr = NativeMethods.GetForegroundWindow()
Dim ProcessID As UInteger = 0
NativeMethods.GetWindowThreadProcessId(hWnd, ProcessID)
Return If(ProcessID <> 0, Process.GetProcessById(ProcessID), Nothing)
End Function
现在你可以像这样使用它:
Dim ActiveProcess As Process = GetActiveProcess()
If ActiveProcess IsNot Nothing AndAlso ActiveProcess.ProcessName = "osk" Then
'Active process is "osk", do something...
End If