我正在编写一个简单的程序来记录点击位置和点击间隔。在设置过程中,用户按“ENTER”将新位置添加到列表中,然后在完成输入位置后按“ESC”。
我得到的一些奇怪的行为是其他按键导致 else if (GetAsyncKeyState(VK_RETURN))
错误地评估为 true。我的猜测是结束 std::cin
的“ENTER”在缓冲区中徘徊并导致了这一点,但我认为 std::cin.get()
而 std::cin.ignore
会解决这个问题。
为什么“ENTER”以外的键导致 (GetAsyncKeyState(VK_RETURN))
评估为真?
void initialSetup() {
int temp = 0;
char input;
std::cout << "Unique sleep times? (y/n): ";
std::cin >> input;
std::cin.get();
std::cin.ignore(100, '\n'); // discards the input buffer
// Ask the user for a sleep each time, or use the same
if (input == 'y') {
uniqueSleepBetweenClicks = true;
}
else {
// Sleep times are constant after each click
std::cout << "Constant sleep time between clicks in ms: ";
std::cin >> constSleepBetweenClicks;
std::cin.get();
std::cin.ignore(100, '\n'); // discards the input buffer
}
std::cout << endl;
std::cout << "***********************************" << endl;
std::cout << "* 'ENTER' to set new position *" << endl;
std::cout << "* 'ESC' when done *" << endl;
std::cout << "***********************************" << endl << endl;
// Add new clicks to the sequence
while (_getch()){
Click click;
if (GetAsyncKeyState(VK_ESCAPE)) {
// Escape keypress ends adding new clicks
break;
}
else if (GetAsyncKeyState(VK_RETURN)) {
// Set the click position
GetCursorPos(&click.point);
std::cout << "Position set to (" << click.point.x << "," << click.point.y << ") " << endl;
if (uniqueSleepBetweenClicks) {
std::cout << "Sleep time in ms: ";
std::cin >> click.sleep;
std::cin.get();
std::cin.ignore(100, '\n'); // discards the input buffer
}
else {
click.sleep = constSleepBetweenClicks;
}
// Add to the list
clickList.push_back(click);
}
}
return;
}
EDIT1:用 VK_SPACE
替换 VK_RETURN
使程序完美运行。问题似乎与 ENTER 键有关。
最佳答案
您没有正确检查返回值,它没有返回 BOOL! GetAsyncKeyState(VK_RETURN) < 0
或 GetAsyncKeyState(VK_RETURN) > 0
取决于您要检查的内容。无论哪种方式,GetAsyncKeyState
不是控制台应用程序的正确方法。
使用 ReadConsoleInput
至 handle input in a console .
如果你想在用户正在另一个应用程序中工作时捕获输入,你应该使用 hooks捕获鼠标和键盘事件。
关于c++ - GetAsyncKeyState(VK_RETURN) 错误地评估为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56624243/