Search code examples
c#windowskeyboard-shortcutsconflictsendkeys

Sending shortcuts (sendkeys) to another application while control key is down


I have an application in which I can select options in a list which, when selected, give focus to another window and send a shortcut (e.g. focus Chrome, and send Ctrl + 3 to go to the third tab).

This works well, but I can also use a shortcut to quickly select an option in the list within my own app (e.g. Ctrl + 3).

The issue is that if the user uses a shortcut within my app, then Ctrl key is down globally, and sending shortcuts to other application will also have the Ctrl key down. (Note that I also send shortcuts to other applications using Alt and Win keys, so using the same control key in both my app and the target app is not an option)

Is there a way to tell Windows that Ctrl is not down when using SendKeys, so that the shortcut works in another application? Is there otherwise an alternative for achieving this?

Here is a simplified example of the code I'm using (C#):

private const int KEYEVENTF_EXTENDEDKEY = 1;
private const int KEYEVENTF_KEYUP = 2;

[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

public void SendCtrl3()
{
    keybd_event(0xA2, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(0x33, 0, KEYEVENTF_EXTENDEDKEY, 0);
    keybd_event(0x33, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    keybd_event(0xA2, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}

Solution

  • It seems that if the key is physically down, there is no way to make it so other apps won't see that key as down.

    The best alternative I found was to use UI Automation.

    http://msdn.microsoft.com/en-us/library/ms747327(v=vs.110).aspx