【发布时间】:2020-05-07 22:08:31
【问题描述】:
我正在尝试检测鼠标按钮点击我检查了微软网站上的一些文档,发现我们可以使用 GetKeyState 函数来检测按钮点击,这是我的代码。
不确定我做错了什么,但是当我按下按钮时,我的输出中没有打印任何内容。
#include <windows.h>
#include <iostream>
#include "stdafx.h"
using namespace std;
void CheckMouseButtonStatus()
{
//Check the mouse left button is pressed or not
if ((GetKeyState(VK_LBUTTON) & 0x80) != 0)
{
cout << "left button pressed" << endl;
}
//Check the mouse right button is pressed or not
if ((GetKeyState(VK_RBUTTON) & 0x80) != 0)
{
cout << "right button pressed" << endl;
}
}
刚刚发现一个朋友正在讲述它的 youtube 视频,我尝试了它仍然没有在输出中得到任何东西
int main()
{
//Check the mouse left button is pressed or not
if ((GetAsyncKeyState(VK_LBUTTON) & 0x80) != 0)
{
cout << "left button pressed" << endl;
}
//Check the mouse right button is pressed or not
if ((GetAsyncKeyState(VK_RBUTTON) & 0x80) != 0)
{
cout << "right button pressed" << endl;
}
}
这个方法有效,但有并发症 -
int main()
{
while (true) {
//Check the mouse left button is pressed or not
if (GetAsyncKeyState(VK_LBUTTON))
{
cout << "left button pressed" << endl;
}
//Check the mouse right button is pressed or not
if (GetAsyncKeyState(VK_RBUTTON))
{
cout << "right button pressed" << endl;
}
}
}
【问题讨论】:
-
@AndreasWenzel 我也试过了,但没有任何输出。
-
& 0x80的意义何在?从the official documentation 可以看出,只有位 0 和 15 是相关的,而不是位 7。它不应该是& 0x8000吗? -
对不起,那些小事让我头疼,我还在上高中。我检查了相同的文档,从那里我得到了这个
VK_BACK 0x08 BACKSPACE key -
GetKeyState 和 AsyncGetKeyState 的返回值都是“SHORT”,根据文档。这是“short int”的 typedef,它是 Windows 平台上的 16 位整数。因此,位编号为 0 到 15。您必须使用
& 0x8000检查 most significant bit,即 15。有关二进制数表示和位掩码的教程,请参阅this page。 -
调试提示:将
GetAsyncKeyState(VK_LBUTTON)返回的值分配给一个变量,这样您就可以在if条件下对其进行测试并将其流式传输到cout。
标签: c++ visual-c++