简体   繁体   中英

keybd_event not registering certain keys

I am creating a personal project to help me press keybinds using a custom GUI. In order to do so, I have a DearImGui frame running within an external window as an independent app.

When I press the button, the app simulates a keypress for each of the keys in the keybind. However, there seems to be an issue while sending the control, shift, and alt keys. I've been struggling with this for over a day now, and just now realized the issue was probably a security measure within Windows. I believe Windows is preventing me from simulating key presses on the control, shift, and alt keys as a preventative against malware that may pretend to be a human.

I decided to include very minimalistic examples since I believe the problem originated from windows and was not an error in my programming.

This example successfully presses F8:

if (ImGui::Button("Button 1", ImVec2(334, 30)))
{
    keybd_event(0x77, 0, 0, 0); //Press down the Key
    keybd_event(0x77, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

While this one should send the combo CTRL + F1, but only registers F1:

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    keybd_event(0x70, 0, 0, 0); //Press down the Key
    keybd_event(VK_CONTROL, 0, 0, 0); //Press down the Key
    keybd_event(0x70, 0, KEYEVENTF_KEYUP, 0); //Release the Key
    keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

Note: all other keys seem to work fine, and I have also tried only sending a ctrl key on its own to see if this was a "you can only do one at a time" problem(it was not.)

You are "pressing down" the keys in the wrong order. You need to "press" down the Ctrl key before the F1 key.

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    keybd_event(VK_CONTROL, 0, 0, 0); //Press down the Key
    keybd_event(VK_F1, 0, 0, 0); //Press down the Key
    keybd_event(VK_F1, 0, KEYEVENTF_KEYUP, 0); //Release the Key
    keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

That being said, keybd_event() is deprecated, please use SendInput() instead, eg:

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    INPUT ips[4] = {};

    ips[0].type = INPUT_KEYBOARD;
    ips[0].ki.wVk = VK_CONTROL;

    ips[1] = ip[0];
    ips[1].ki.wVk = VK_F1;

    ips[2] = ip[1];
    ips[2].ki.dwFlags = KEYEVENTF_KEYUP;

    ips[3] = ips[0];
    ips[3].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(4, ips, sizeof(INPUT));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM