Detecting Key Presses Across Applications in Powershell

邮差的信 提交于 2019-12-11 05:00:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!