Blog content

Latest posts

Active categories:

More tags ...

By date:

    (No recent posts)

Blog calendar

August 2017
Mo Tu We Th Fr Sa Su
 << Jul Sep >>
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

Blog features

RSS feed icon RSS feed

RSS comment feed icon RSS comment feed

Querying key states in PowerShell

posted by Martin Rubli at 13:45

Did you ever wonder how to check key states in a PowerShell script? This can be handy in situations where you want your script to behave slightly differently when, for example, the Shift key is pressed.

The first instinct would be to use something like the Windows.Forms.Control.ModifierKeys method, which even works for .NET console applications. However, in PowerShell said method always returns None, so that won't work.

Here's a slightly uglier method that provides a workaround:

function Get-KeyState([uint16]$keyCode)
{
  $signature = '[DllImport("user32.dll")]public static extern short GetKeyState(int nVirtKey);'
  $type = Add-Type -MemberDefinition $signature -Name User32 -Namespace GetKeyState -PassThru
  return [bool]($type::GetKeyState($keyCode) -band 0x80)
}

The function can be used as follows:

$VK_SHIFT = 0x10
Write-Host "Shift key pressed:" (Get-KeyState($VK_SHIFT))

For more information on how to query other keys you can consult the documentation on the GetKeyState() function and Virtual Key Codes.


  1. MarkusXKC says:

    You could also try one of the following commands:

    [System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::LeftShift)
    # True only if left shift key is pressed, False for right shift key
    $blnIsShiftKeyDown = [System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::LeftShift) `
    -or [System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::RightShift)
    $blnIsShiftKeyDown
    # True if ANY shift key is pressed

    [System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::Enter)
    [System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::F1)

    [System.Windows.Forms.Control]::IsKeyLocked([System.Windows.Forms.Keys]::CapsLock)
    [System.Windows.Forms.Control]::IsKeyLocked([System.Windows.Forms.Keys]::NumLock)
    [System.Windows.Forms.Control]::IsKeyLocked([System.Windows.Forms.Keys]::Scroll)

Leave a comment

Your comment: