获取鼠标按钮请点击

时间:2020-05-07 22:08:31

标签: c++ visual-c++

我试图检测鼠标单击,我检查了Microsoft网站上的一些文档,发现我们可以使用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视频,我试过它在Output中仍然没有任何内容

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;
        }
    }

}

1 个答案:

答案 0 :(得分:0)

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

#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上的说明,因为有时这可能会引起问题。