-1

I was making a program to send keystrokes to another window and I got it all working, but I had to go online and find a function to do the keystroke portion itself. It works but I have no idea what it is actually doing. Can someone comment each line of this function explaining what it's doing?

void GenerateKey(int vk, BOOL bExtended) {

    KEYBDINPUT  kb = {0};
    INPUT       Input = {0};

    /* Generate a "key down" */
    if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
    kb.wVk  = vk;
    Input.type  = INPUT_KEYBOARD;
    Input.ki  = kb;
    SendInput(1, &Input, sizeof(Input));

    /* Generate a "key up" */
    ZeroMemory(&kb, sizeof(KEYBDINPUT));
    ZeroMemory(&Input, sizeof(INPUT));
    kb.dwFlags  =  KEYEVENTF_KEYUP;
    if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
    kb.wVk = vk;
    Input.type = INPUT_KEYBOARD;
    Input.ki = kb;
    SendInput(1, &Input, sizeof(Input));

    return;
}

Here's an example of a call to it:

GenerateKey('C', FALSE);    // Sends keystroke 'c'

This sends the keystroke 'c'.

This function only works with capital letters and seems to only work with specific hex codes. For example, to send a carriage return (enter key), here is the call:

GenerateKey(0x0D, FALSE);   // Sends carriage return

However, if I try sending a question mark (hex 0x3F) with either of these calls, nothing happens:

GenerateKey(0x3F, FALSE);  // Nothing happens
GenerateKey('?', FALSE);   // Nothing happens

Can anyone see why those wouldn't work?

Also, can someone explain what the second argument, BOOL bExtended, is for? Changing between TRUE and FALSE seems to make no difference in the keystrokes it sends.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

4

Your GenerateKey function makes internal use of the SendInput function from the Win32 API, which synthesizes keyboard input.

You can find all of the information you need to understand how that function works and how to call it by reading the MSDN documentation for that function.

The vk parameter is a virtual key code, listed here.

If the bExtended parameter is TRUE, then the KEYEVENTF_EXTENDEDKEY flag is set, which according to the documentation means that "the scan code was preceded by a prefix byte that has the value 0xE0 (224)".

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574