您可以使用GetForegroundWindow
和GetWindowThreadProcessId
API 为您执行此操作。这是一个简单的例子:
''' <summary>The GetForegroundWindow function returns a handle to the foreground window.</summary>
''' <returns>The return value is a handle to the foreground window. The foreground window can be NULL in certain circumstances, such as when a window is losing activation. </returns>
<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 Integer) As Integer
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Task.Run(AddressOf KeySender)
End Sub
Private Sub KeySender()
While (True)
Dim fgWin = GetForegroundWindow()
Dim fgPid As New Integer()
GetWindowThreadProcessId(fgWin, fgPid)
Dim proc = System.Diagnostics.Process.GetProcessById(fgPid)
Console.WriteLine(proc.ProcessName)
If (proc.ProcessName = "notepad") Then
SendKeys.SendWait("A")
End If
System.Threading.Thread.Sleep(1000)
End While
End Sub