Search code examples
c#powershellautomationpowershell-isepester

How to handle multiple key press simultaneously in powershell? Eg:Windows logo key + Alt + PrtScn:


Tried the below code in powershell ISE but it accept only 1st key (Pressing Win) after that it accepts next key as 'g'.

[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.SendKeys]::sendwait("(^{ESCAPE})g")

But I want to Press the Win+g at a time to open some applications like xbox game bar.

Can anyone guide me on this?


Solution

  • It can't be done with native SendWait method but we can use WinAPI to do this as shown here https://social.msdn.microsoft.com/Forums/vstudio/en-US/f2d88949-2de7-451a-be47-a7372ce457ff/send-windows-key?forum=csharpgeneral

    $code = @'
    namespace SendTheKeys {
      class SendIt {
       public static void Main(string[] args) {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
            private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
    
            private const int KEYEVENTF_EXTENDEDKEY = 1;
            private const int KEYEVENTF_KEYUP = 2;
    
            public static void KeyDown(Keys vKey)
            {
                keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
            }
    
            public static void KeyUp(Keys vKey)
            {
                keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
            }
        KeyDown(Keys.LWin);
        KeyDown(Keys.G);
        KeyUp(Keys.LWin);
        KeyUp(Keys.G);
      }
     }
    }
    '@
    Add-Type -TypeDefinition $code -Language CSharp
    [SendTheKeys.SendIt]::Main()