I’m trying to emulate key down and key up in windows. However the behaviour is not working as expected.
In main(), when I press ‘a’, the ‘b’ key should be pressed and stay pressed for 3 seconds. however, it seems to just do a press and immediately release. I expect it to press ‘b’ and keep it pressed for 3 seconds, then release the key.
When sending mouse buttons using SendInput it works. But for keyboard inputs it doesnt want to respect the keydown/keyup flags.
For context, I’m writting a program that uses a single mouse+keyboard to work between multiple machines(cross platform). Why not just use Synergy or some other key+mouse sharing programs? Because I want to learn new things.
The linux versions both work, its just the windows keyboard part that doesnt want to work.
I also asked chat GPT, it told me that this was right, then we got into a circuolar argument, so I need some help from real people, lol.
#include <iostream>
#include <Windows.h>
void SimulateKeyboard(unsigned int keycode, bool press){
#ifdef _WIN32
INPUT input = {0};
input.type = INPUT_KEYBOARD;
input.ki.wVk = keycode;
input.ki.dwFlags = press ? 0 : KEYEVENTF_KEYUP; // Key down
SendInput(1, &input, sizeof(INPUT));
#elif __linux__
//It works right in linux
XTestFakeKeyEvent(xConn.display, osKeyCode, press ? True : False, 0);
XFlush(xConn.display);
#endif
}
void SimulateMouse(int button, bool press){
// 0 = left, 1 = right, 2 = middle
#ifdef _WIN32
DWORD buttonFlag = press ?
(button == 0) ? MOUSEEVENTF_LEFTDOWN :
(button == 1) ? MOUSEEVENTF_RIGHTDOWN :
MOUSEEVENTF_MIDDLEDOWN
:
(button == 0) ? MOUSEEVENTF_LEFTUP :
(button == 1) ? MOUSEEVENTF_RIGHTUP :
MOUSEEVENTF_MIDDLEUP;
INPUT input = {0};
input.type = INPUT_MOUSE;
input.mi.dwFlags = buttonFlag;
SendInput(1, &input, sizeof(INPUT));
#elif __linux__
//1 left, 2 mid, 3 right for xdotool
//Hacky and probably unsafe solution, will fix later, but works for now
if(button==0) system(press?"xdotool mousedown 1":"xdotool mouseup 1");
if(button==1) system(press?"xdotool mousedown 3":"xdotool mouseup 3");
if(button==2) system(press?"xdotool mousedown 2":"xdotool mouseup 2");
#endif
}
void main(){
while(1){
if(GetAsyncKeyState('A')&0x8000){
//This works as expected using SendInput; presses LMB and keeps it pressed for 3000 ms then releases LMB
//SimulateMouse(0, true);
//Sleep(3000);
//SimulateMouse(0, false);
//This does NOT work as expected using SendInput; this presses B and releases it imediatly producing a key press. It should be holding down for 3 seconds then releasing
SimulateKeyboard('B', true);
Sleep(3000);
SimulateKeyboard('B', false);
}
}
return;
}