Domanda

I'm trying to make a program which sends two additional key presses for every left mouse button press I make. This all works fine except when I'm in another program (in my case it's a game), then it does sense the left mouse button being pressed but it does not press the additional two virtual keys for me. The entire code:

#include <Windows.h>
#include <iostream>
int main ()
{
INPUT ip;
bool press = false;
int i = 0;
while ( true )
{
    if ( GetKeyState( VK_LBUTTON) < 0 & !press )
    {
        std::cout << "press" << i++ << "\n";
        // PRESS F8
        ip.type = INPUT_KEYBOARD;
        ip.ki.wScan = 0x42; // hardware scan code for key
        ip.ki.time = 0;
        ip.ki.dwExtraInfo = 0;
        ip.ki.wVk = 0x77; // virtual-key code 

        ip.ki.dwFlags = 0; // 0 for key press
        SendInput(1, &ip, sizeof(INPUT));
        if (GetKeyState( VK_F8) < 0) { std::cout << "press f8 \n";}
        ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
        SendInput(1, &ip, sizeof(INPUT));

        ip.ki.dwFlags = 0; // 0 for key press
        SendInput(1, &ip, sizeof(INPUT));
        ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
        SendInput(1, &ip, sizeof(INPUT));

        press = true;
    }
    if ( GetKeyState( VK_LBUTTON) >= 0 )
    {
        press = false;
    }
}
return(0);
}

Now I have read everything I could find regarding this, which isn't all that much btw, and I think it has something to do with using scancodes instead of virtualkeycodes. The problem is that when I make this ip.ki.wScan = 0; and ip.ki.wVk = 0x77; it will do it right but not inside the game, same when I use both scancode and VKcode. But when VKcode is zero it stops pressing the F8 key even whem I'm not in the game.

So my question is: How do I make a system-wide virtual key press that will also work when I'm not in desktop?

È stato utile?

Soluzione

Ok I found out how to use the scancodes to make the virtual keypress

// PRESS F8
        ip.type = INPUT_KEYBOARD;
        ip.ki.wScan = MapVirtualKey(VK_F8, 0); // hardware scan code for key
        ip.ki.time = 0;
        ip.ki.dwExtraInfo = 0;
        ip.ki.wVk = 0;//0x77; // virtual-key code 

        ip.ki.dwFlags = KEYEVENTF_SCANCODE; // 0 for key press
        SendInput(1, &ip, sizeof(INPUT));
        if (GetKeyState( VK_F8) < 0) { std::cout << "press f8 \n";}
        ip.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
        SendInput(1, &ip, sizeof(INPUT));

The dwFlags should be KEYEVENTF_SCANCODE else it will automatically use the VK code to determine which is supposed to be pressed.

Now it still does not send the virtual key press to the game I'm running. Whenever I'm in this game it just doesn't work, how can I fix this??

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top