Вы можете использовать Вызов платформы (для краткости P / Invoke ) для доступа к функциям WinAPI GetForegroundWindow()
и GetWindowThreadProcessId()
.
Вы можете использовать GetForegroundWindow()
, чтобы получить дескриптор окна текущего / активного окна, а затем вызвать GetWindowThreadProcessId()
, чтобы получить идентификатор процесса этого окна. Затем вы можете использовать этот идентификатор для получения экземпляра .NET Process
класса , с помощью которого вы можете легко получить доступ к имени процесса и т. Д.
Для начала создайте класс с именем 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