Search code examples
c#keyshift

How to send the left shift key?


I am trying to send a key into another open process in Firefox. I am supposed to send the Left Shift key, but this is without any luck.

I tried googling these answers but all I end up with were extern methods using nuggets or people using the regular shift. I tried many ways of sending the Left Shift using Enum of the Left Shift or Sendkey.Send("{LSHIFT}") and much more but none are working for me. I wish to know if there is any suitable way for me to send the Left Shift key.

This is my code so far:

public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Keys pressed = (Keys)vkCode;
        MessageBox.Show(pressed.ToString());
        switch (pressed)
        {
            case Keys.Insert:
                {
                    SendKeys.Send("{LSHIFT}");
                }
            break;
        }
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

I have seen lists with and lists without the left shift key, but either way they pop up as error 'invalid key'.

Thank you.


Solution

  • Use keybd_event API with "VK_LSHIFT" virtual key code :

    const byte VK_LSHIFT = 0xA0;
    const uint KEYEVENTF_KEYUP = 0x0002;
    
    [DllImport("user32.dll")]
    private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
    
    static void Main(string[] args)
    {
        keybd_event(VK_LSHIFT, 0, 0, 0);
        Thread.Sleep(100);
        keybd_event(VK_LSHIFT, 0, KEYEVENTF_KEYUP, 0);
    }