windowspowershellvbscriptsendkeys

How to emulate keypress combination without activating Window using Win32 API


I would like to emulate Ctrl+Alt+L keypress combination (which a hidden process running in memory is listening for). So... I can't activate a GUI window that's not there (using traditional SendKeys).

I can't seem to find a single working script anywhere that can help me do this. The closest I found was the Keypress script below which seems to be limited to only a single character press (no key combinations).

https://www.reddit.com/r/PowerShell/comments/3qk9mc/keyboard_keypress_script/


Solution

  • This is a demonstration with CTRL+ESCAPE. Easy to modify for your needs. A list of keyboard codes is here: http://www.kbdedit.com/manual/low_level_vk_list.html

    But be careful while testing. If a key isn't properly released, strange effects can be happen!

    $keyboardEvent = Add-Type –memberDefinition @" 
        [DllImport("user32.dll")] 
        public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
    "@ -name "keyboardEvent" -namespace Win32Functions –passThru
        
    $key_down    = 0x00
    $key_up      = 0x02
       
    $vk_lcontrol = 0xA2
    $vk_alt      = 0x12
    $vk_l        = 0x4C
    $vk_escape   = 0x1B
    $vk_windows  = 0x5B
        
    # Press CTRL+ESC => Same as Windows Key
    [Win32Functions.keyboardEvent]::keybd_event([byte]$vk_lcontrol, [byte]0, [UInt32]$key_down, [UIntPtr]::Zero)
    [Win32Functions.keyboardEvent]::keybd_event([byte]$vk_escape, [byte]0, [UInt32]$key_down, [UIntPtr]::Zero)
    Start-Sleep 1
        
    # Release CTRL+ESC 
    [Win32Functions.keyboardEvent]::keybd_event([byte]$vk_lcontrol, [byte]0, [UInt32]$key_up, [UIntPtr]::Zero)
    [Win32Functions.keyboardEvent]::keybd_event([byte]$vk_escape, [byte]0, [UInt32]$key_up, [UIntPtr]::Zero)
    Start-Sleep 1