如何检测鼠标是否被按下,而不仅仅是点击



程序必须在按下WASD键时进行检测,但只能在按下左侧按钮时进行检测。

我正在尝试这个代码,但它只在我点击时写入。

#include <iostream>
#include <Windows.h>

using namespace std;
int KeyPressed(int key){
return (GetAsyncKeyState(key) & 0x8000 != 0);
}

int main()
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = 0;
input.ki.time = 0;
input.ki.dwExtraInfo = 0;
while (true){
if(KeyPressed(VK_LBUTTON)){
input.ki.wVk = 0x57;    //W
input.ki.dwFlags = 0;
SendInput(1, &input, sizeof(INPUT));
input.ki.wVk = 0x41;    //A
input.ki.dwFlags = 0;
SendInput(1, &input, sizeof(INPUT));
input.ki.wVk = 0x53;    //S
input.ki.dwFlags = 0;
SendInput(1, &input, sizeof(INPUT));
input.ki.wVk = 0x44;    //D
input.ki.dwFlags = 0;
SendInput(1, &input, sizeof(INPUT));
}
}
}

当您释放鼠标按钮时,您并没有模拟释放的WASD键。

此外,用cInputs=1调用SendInput()(几乎总是(是一个错误。当同时发送多个事件时,请使用多个INPUTs的数组。这可以避免任何比赛条件,否则其他事件可能会交织在模拟事件之间。

试试这个:

#include <windows.h>
int KeyPressed(int key){
return (GetAsyncKeyState(key) & 0x8000 != 0);
}

int main()
{
INPUT inputs[4] = {};
bool mouseIsDown = false;
for(int i = 0; i < 4; ++i) {
inputs[i].type = INPUT_KEYBOARD;
inputs[i].ki.wScan = 0;
inputs[i].ki.time = 0;
inputs[i].ki.dwExtraInfo = 0;
}
inputs[0].ki.wVk = 0x57;    //W
inputs[1].ki.wVk = 0x41;    //A
inputs[2].ki.wVk = 0x53;    //S
inputs[3].ki.wVk = 0x44;    //D
while (true) {
if (KeyPressed(VK_LBUTTON)) {
if (!mouseIsDown){
mouseIsDown = true;
for(int i = 0; i < 4; ++i) {
inputs[i].ki.dwFlags = 0;
}
SendInput(4, inputs, sizeof(INPUT));
}
}
else if (mouseIsDown) {
mouseIsDown = false;
for(int i = 0; i < 4; ++i) {
inputs[i].ki.dwFlags = KEYEVENTF_KEYUP;
}
SendInput(4, inputs, sizeof(INPUT));
}
Sleep(0);
}
}

相关内容

最新更新