问题
This is a post that can be found on Powershell.com via Wayback machine. It is from 2015 and is not on the site anymore. A link to it is here: Detecting Key Presses Across Applications.
This post is meant to be Archival.
回答1:
By accessing the Windows low-level system calls, PowerShell can query the keyboard for pressed keys. The following example waits until the user presses 'A'. This is a simple example that does not consider the state of the SHIFT keys, nor does it check virtual keys. However, it detects key presses across all open applications. So PowerShell will detect a pressed "A" key even if it does not have focus, and you entered "A" into a different application.
#requires -Version 2
$signature = @'
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern short GetAsyncKeyState(int virtualKeyCode);
'@
# load signatures and make members available
$API = Add-Type -MemberDefinition $signature -Name 'Keypress' -Namespace API -PassThru
# wait for 'A'
$waitFor = 'A'
$ascii = [byte][char]$waitFor.ToUpper()
do
{
Start-Sleep -Milliseconds 40
} until ($API::GetAsyncKeyState($ascii) -eq -32767)
来源:https://stackoverflow.com/questions/46010963/detecting-key-presses-across-applications-in-powershell