【问题标题】:Get Mouse button Click获取鼠标按钮单击
【发布时间】: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 我也试过了,但没有任何输出。
  • &amp; 0x80 的意义何在?从the official documentation 可以看出,只有位 0 和 15 是相关的,而不是位 7。它不应该是 &amp; 0x8000 吗?
  • 对不起,那些小事让我头疼,我还在上高中。我检查了相同的文档,从那里我得到了这个VK_BACK 0x08 BACKSPACE key
  • GetKeyState 和 AsyncGetKeyState 的返回值都是“SHORT”,根据文档。这是“short int”的 typedef,它是 Windows 平台上的 16 位整数。因此,位编号为 0 到 15。您必须使用 &amp; 0x8000 检查 most significant bit,即 15。有关二进制数表示和位掩码的教程,请参阅this page。
  • 调试提示:将GetAsyncKeyState(VK_LBUTTON) 返回的值分配给一个变量,这样您就可以在if 条件下对其进行测试并将其流式传输到cout。

标签: c++ visual-c++


【解决方案1】:

使用GetAsyncKeyState() 并使用按位与来检查是否设置了最低有效位,这表示新的按键,而不是之前检测到的按键。

#include <windows.h>
#include <iostream>

int main()
{
    while (true)
    {
        //Check the mouse left button is pressed or not
        if (GetAsyncKeyState(VK_LBUTTON) & 1)
        {
            std::cout << "left button pressed" << std::endl;
        }
        //Check the mouse right button is pressed or not
        if (GetAsyncKeyState(VK_RBUTTON) & 1)
        {
            std::cout << "right button pressed" << std::endl;
        }

    }
    return 0;
}

GetAsyncKeyState 非常适合简单的测试和学习目的,但最好使用普通的 Windows 消息队列进行任何输入检测。请记住,GAKS 是全球性的,它会检测所有进程上的按键,而不仅仅是您的。阅读 MSDN 上的注释,因为有时这会导致问题。

【讨论】:

  • 正如您链接到的页面上所指出的,返回值的最低有效位仅用于向后兼容 16 位 Windows。它不应该用于 32 位(或 64 位)应用程序,因为它不可靠。
猜你喜欢
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 2012-01-12
  • 2010-12-16
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多