Get Mouse button Click

Viewed 947

I am trying to detect mouse button clicks i checked some documentation on Microsoft website and found we can use GetKeyState function to detect button clicks, here's my code.

Not sure what i am doing wrong her but i am not getting anything printed in my Output when i press buttons.

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

just found a youtube video a buddy was telling about it and i tried it still didn't got anything in 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;
    }
}

This one worked but with complications -

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 Answers

Use GetAsyncKeyState() and use a bitwise AND to check if the least significant bit is set, this indicates a new key press, and not one that was previously detected.

#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 is great for simple testing and learning purposes but it's best to use the normal Windows message queue for any input detection. Keep in mind GAKS is global, it will detect key presses on all processes, not just yours. Read the remarks on MSDN because sometimes that can cause a problem.

Related