Sending Keystrokes

Have you ever wanted to send a key to another application? Seems simple, right? Just post a WM_CHAR message to that application. It turns out that doesn't work well for a variety of reasons. Luckily, it is easy to do by calling keybd_event, This call takes 4 arguments. The first is the virtual key code you want the system to "pretend" you just pressed. The next is the key's scan code (you can get that by calling MapVirtualKey). Next, you need to tell Windows if the key was up (KEYEVENTF_KEYUP) or down (0). The final argument is some extra information you won't often use. For example, to send an F1 keystroke you might use the following code:
keybd_event(VK_F1,MapVirtualKey(VK_F1,0), 0,0);
keybd_event(VK_F1,MapVirtualKey(VK_F1,0), KEYEVENTF_KEYUP,0);



Don't forget, virtual key codes are not ASCII codes. If you want to send an uppercase A, for example, you'd need to explicitly send the shift key. Perhaps, like this:

keybd_event(VK_SHIFT,MapVirtualKey(VK_SHIFT,0), 0,0);
keybd_event('A',MapVirtualKey('A',0), 0,0);  // by itself this would be a lower case A!
keybd_event('A',MapVirtualKey('A',0), KEYEVENTF_KEYUP,0);
keybd_event(VK_SHIFT,MapVirtualKey(VK_SHIFT,0), KEYEVENTF_KEYUP,0);