Keyboard Hook

 

Capture global keyboard events in PowerShell ISE.
(warning, this is effectively a key logger for PowerShell)

After spending a lot of time on Goole looking for solutions to capture keyboard events in ISE and finding that all of the solutions only worked in the PowerShell command console, not ISE, I turned to GitHub for a head start in building something that would allow ISE to detect any keyboard event.

It is a .Net class that supports events in PowerShell

Download the DLL into your PowerShell directory using this link

https://1drv.ms/u/s!ApGpqMMpRLhijfNq4VZM-E-H5WiIEw

Remember to unblock the file after saving it.

Use it in ISE like this…


add-type -Path '.\documents\WindowsPowerShell\VISE_WinKeyboardHook.dll'
$KeyboardInterceptor = new-object VISE.WinKeyboardHook.KeyboardInterceptor
function HandleKeyDown($keyId)
{
write-host $keyID.KeyCode
if($keyID.KeyCode -eq "Escape"){
$KeyboardInterceptor.StopCapturing()
}
}
Unregister-Event -SourceIdentifier KeyDown -ErrorAction SilentlyContinue
$keyevent = Register-ObjectEvent -InputObject $KeyboardInterceptor -EventName KeyDown -SourceIdentifier KeyDown -Action {HandleKeyDown($event.sourceEventArgs)}
$KeyboardInterceptor.StartCapturing()

The $event.sourceEventArgs returns several properties that can be accesses in the HandleKeyDown function:

  • $keyID.KeyChar
  • $keyID.KeyCode
  • $keyID.KeyData
  • $keyID.KeyValue
  • $keyID.Modifiers
  • $keyID.Shift
  • $keyID.Alt
  • $keyID.Control

The one I use most is KeyData as this returns a string with all the current keys that are down. The following shows the output for all properties as a <ctrl><alt>d keyboard sequence is pressed..

KeyCode LControlKey
KeyData LControlKey
KeyValue 162
Modifiers None
Shift False
Alt False
Control False
—————————
KeyCode LMenu
KeyData LMenu, Control
KeyValue 164
Modifiers Control
Shift False
Alt False
Control True
—————————
KeyCode D
KeyData D, Control, Alt
KeyValue 68
Modifiers Control, Alt
Shift False
Alt True
Control True

There is also a KeyUp event so you can wait until a key is released for things like volume settings or PTZ camera movements.

It is particularly useful for keyboards that have extra function keys that you can use to automate anything. I’ll have some sample for using this MX Light shortly.

Code for this dll was largely copied from a codeplex project and includes this license https://github.com/lontivero/Open.WinKeyboardHook/blob/master/LICENSE

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s