Detecting Key Presses across Applications

by Dec 8, 2015

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 $signatures -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)

We will expand on this tomorrow when we show how you can use this approach to create a keylogger.

Twitter This Tip! ReTweet this Tip!