Checking for mouse clicks?

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
gibxam
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 3
Joined: Sat Oct 25, 2008 1:19 am

Checking for mouse clicks?

Post by gibxam »

Hello Everyone,

Especially Falco and the rest of the dev team. I've been a long time viewer of your guys' videos, and I know everyone has said it a million times, but good job and keep up the great work :)!

I am writing a C++ console app and trying to check to see if the left mouse button is being held down. The problem is that the struct I am using only checks for one click and not to see if it is being held down. I found some stuff on MouseUp and MouseDown on msdn but its so difficult to decipher what they are trying to teach you on their website, especially with each example being in java c# c++ basic, and whatever else they have on there. What this is going to be used for is to create a dos-like helicopter replica, where the user holds down the left mouse button the helicopter goes up, and likewise when they let go it goes down. To try and limit the amount of code I'm posting on here I have posted the section of interest. If you need more info please let me know and I will post more.

Code: Select all

case MOUSE_EVENT:
    if (irInBuf[i].Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
    {
		mouseState = MOUSE_DOWN;
		while(mouseState == MOUSE_DOWN)
		{
			ReadConsoleInput(hStdin,irInBuf,128,&cNumRead);
			if(irInBuf[i].Event.MouseEvent.dwButtonState != FROM_LEFT_1ST_BUTTON_PRESSED)
			{
				mouseState = MOUSE_UP;
			}
			printf("Clicking...\n");
		}
    }
    break;
just note that mouseState is a global that I created and MOUSE_DOWN and MOUSE_UP are enums. But hopefully I won't have to use these If i can figure out how to check for the mousepressed and mousereleased events. Also the place I am thinking of putting the events is mousePressed in the first if statement, and mouse released in the second one. Thanks for your help in advanced. Let me know if I left out any info.

-Max
User avatar
MarauderIIC
Respected Programmer
Respected Programmer
Posts: 3406
Joined: Sat Jul 10, 2004 3:05 pm
Location: Maryland, USA

Re: Checking for mouse clicks?

Post by MarauderIIC »

You're close. Try surrounding it with the dwEventFlags == 0, I think the issue is maybe that the state doesn't persist between events?
Normally one would use & instead of == but for your usage it shouldnt matter, I think.

Code: Select all

INPUT_RECORD InRec;
if (InRec.EventType == MOUSE_EVENT)
        {
            if (InRec.Event.MouseEvent.dwEventFlags == 0) //a mouse button event that is not move or doubleclick has happened
            {
                if (InRec.Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED)
                {
                    cout << "Down" << flush;
                }
                else
                {
                    cout << "Up  " << flush;
                }
I shamelessly lifted this from http://www.adrianxw.dk/SoftwareSite/Con ... oles5.html and I don't agree with his capitalization conventions. Also that's why the tabbing is off. And the brackets.
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
gibxam
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 3
Joined: Sat Oct 25, 2008 1:19 am

Re: Checking for mouse clicks?

Post by gibxam »

Hey Marauder,

Thanks for the quick response. The code you posted does not work, it compiles and runs fine however it never gets past the first if statement. I'm going to check out the link you posted and post back with results :)

-Max
User avatar
MarauderIIC
Respected Programmer
Respected Programmer
Posts: 3406
Joined: Sat Jul 10, 2004 3:05 pm
Location: Maryland, USA

Re: Checking for mouse clicks?

Post by MarauderIIC »

Hope you get it to work, cause the code I pasted was pretty much from there.
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
gibxam
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 3
Joined: Sat Oct 25, 2008 1:19 am

Re: Checking for mouse clicks?

Post by gibxam »

Hey I still need to read through this to fully understand what my friend on 3dbuzz is doing but I thought some people may be interested in this. I give full credits to enhzflep on 3dbuzz, check it out.

Code: Select all

#include <windows.h>
#include <wincon.h>
#include <stdio.h>

VOID MouseEventProc(MOUSE_EVENT_RECORD);
VOID ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD);
VOID KeyEventProc(KEY_EVENT_RECORD);
VOID GetInputEvents(VOID);

bool lastLeftState=false;
bool lastRightState=false;
bool lastMiddleState=false;
DWORD lastButtonState = 0;
COORD lastMousePosition ={0,0};

HANDLE buf1, buf2, curBuf;
int bufNum=1;

bool coordsSame(COORD c1, COORD c2)
{
    bool result = false;
    if (c1.X == c2.X)
        if (c1.Y == c2.Y)
            result = true;
    return result;
}

int main()
{
    HANDLE hStdin, hStdout;
    DWORD cNumRead, fdwMode, fdwSaveOldMode, i;
    INPUT_RECORD irInBuf[128];
    DWORD err;

    int conWidth, conHeight;

    // Get the standard input handle.
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE)
    {
        err = GetLastError();
        DebugBreak();
    }


    // Get the standard input handle.
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hStdout == INVALID_HANDLE_VALUE)
    {
        err = GetLastError();
        DebugBreak();
    }


// Save the current input mode, to be restored on exit.
    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )
    {
        err = GetLastError();
        DebugBreak();
    }

    // Enable the window and mouse input events.
    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;// | ENABLE_ECHO_INPUT;
    if (! SetConsoleMode(hStdin, fdwMode) )
    {
        err = GetLastError();
        DebugBreak();
    }

    buf1 = CreateConsoleScreenBuffer(

    GENERIC_READ|GENERIC_WRITE,	// access flag
    FILE_SHARE_READ|FILE_SHARE_WRITE,	// buffer share mode
    NULL,	// pointer to security attributes
    CONSOLE_TEXTMODE_BUFFER,	// type of buffer to create
    NULL 	// reserved
   );

    curBuf = buf1;
    SetConsoleActiveScreenBuffer(curBuf);

    // get the size of the window - top-left is 0,0    bot-right is width-1, height-1
    CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo;
    GetConsoleScreenBufferInfo(buf1, &consoleScreenBufferInfo);
    conWidth = consoleScreenBufferInfo.srWindow.Right;
    conHeight = consoleScreenBufferInfo.srWindow.Bottom;
    printf("Console size: %d, %d\n", conWidth+1, conHeight+1);

    COORD origin = {0,0};
    DWORD numCharsSet;


    FillConsoleOutputAttribute(curBuf,
                                                FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
                                                (conWidth+1)*(conHeight+1),
                                                origin,
                                                &numCharsSet);
    FillConsoleOutputCharacter(curBuf, ' ', (conWidth+1)*(conHeight+1), origin, &numCharsSet);

    // Loop to read and handle the input events.
    while (1)
    {
        // Wait for the events.
        ReadConsoleInput(
        hStdin, // input buffer handle
        irInBuf, // buffer to read into
        128, // size of read buffer
        &cNumRead); // number of records read
        // MyErrorExit("ReadConsoleInput");
        DWORD foo = GetLastError();

        char message[200];

        // Dispatch the events to the appropriate handler.
        for (i = 0; i < cNumRead; i++)
        {
            //FillConsoleOutputCharacter(curBuf, ' ', (conWidth+1)*(conHeight+1), origin, &numCharsSet);
            SetConsoleCursorPosition(curBuf, origin);

            switch(irInBuf[i].EventType)
            {

                case MOUSE_EVENT:

                    //=============================================
                    //
                    //
                    // Handle mouse-wheel roll-events
                    //
                    if (irInBuf[i].Event.MouseEvent.dwEventFlags & MOUSE_WHEELED)
                    {
                        FillConsoleOutputCharacter(curBuf,' ',(conWidth+1),origin,&numCharsSet);
                        sprintf(message, "Mouse rolled: %d\n", (signed short )HIWORD(irInBuf[i].Event.MouseEvent.dwButtonState) / 120);
                        WriteConsole(curBuf, message, strlen(message), &numCharsSet, NULL);
                        //printf("Mouse rolled: %d\n", (signed short )HIWORD(irInBuf[i].Event.MouseEvent.dwButtonState) / 120);
                    };

                    //=============================================
                    //
                    //
                    // Handle mouse button events
                    //
                    if (irInBuf[i].Event.MouseEvent.dwEventFlags == 0)  // 0 = BUTTON_PRESS_OR_RELEASE
                    {
                        FillConsoleOutputCharacter(curBuf,' ',(conWidth+1),origin,&numCharsSet);
                        WriteConsole(curBuf, ".button event.", strlen(".button event."), &numCharsSet, NULL);
                        sprintf(message, ".dwButtonState: 0x%08x.", irInBuf[i].Event.MouseEvent.dwButtonState);
                        WriteConsole(curBuf, message, strlen(message), &numCharsSet, NULL);

                        //--------------------------------------------------------------
                        // check for left mouse button click/release events
                        //
                        if (lastLeftState)
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED)
                            {
                                // Left button was pressed and still is - do nothing
                            }
                            else
                                {   // left button was pressed and now isn't - do onLeftRelease code
                                    WriteConsole(curBuf, "left released!", strlen("left released!"), &numCharsSet, NULL);
                                }

                        else // Left button wasn't pressed
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED)
                            { // wasn't pressed and now is - do onLeftPress code
                                WriteConsole(curBuf, "left pressed!", strlen("left pressed!"), &numCharsSet, NULL);
                            }

                        //----------------------------------------------------------------
                        // check for right mouse button click/release events
                        //
                        if (lastRightState)
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & RIGHTMOST_BUTTON_PRESSED)
                            {
                                // Right was pressed and still is - do nothing
                            }
                            else
                                {   // right button was pressed and now isn't - do onRightRelease code
                                    WriteConsole(curBuf, "right released!", strlen("right released!"), &numCharsSet, NULL);
                                }

                        else // Right button wasn't pressed
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & RIGHTMOST_BUTTON_PRESSED)
                            { // wasn't pressed and now is - do onRightPress code
                                WriteConsole(curBuf, "right pressed!", strlen("right pressed!"), &numCharsSet, NULL);
                            }

                        //----------------------------------------------------------
                        // check for mouse wheel click/release events
                        //
                        if (lastMiddleState)
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED)
                            {
                                // was pressed and still is - do nothing
                            }
                            else
                            {   // middle button was pressed and now isn't - do onMiddleRelease code
                                WriteConsole(curBuf, "middle released!", strlen("middle released!"), &numCharsSet, NULL);
                            }
                        else // Middle button wasn't pressed
                            if (irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED)
                            { // wasn't pressed and now is - do onMiddlePress code
                                WriteConsole(curBuf, "middle pressed!", strlen("middle pressed!"), &numCharsSet, NULL);
                            }

                        WriteConsole(curBuf, "\n", strlen("\n"), &numCharsSet, NULL);
                    }


                    //=============================================
                    //
                    //
                    // Handle mouse movement messages
                    //
                    if (irInBuf[i].Event.MouseEvent.dwEventFlags & MOUSE_MOVED)
                    {
                        // sometimes we get MOUSE_MOVED messages yet the position hasn't changed.
                        if ( ! coordsSame(lastMousePosition, irInBuf[i].Event.MouseEvent.dwMousePosition))
                        {
                                FillConsoleOutputCharacter(curBuf,' ',(conWidth+1),origin,&numCharsSet);
                                WriteConsole(curBuf, "Mouse Moved\n", strlen("Mouse Moved\n"), &numCharsSet, NULL);
                                sprintf(message, "Cursor: [%2d,%2d]", irInBuf[i].Event.MouseEvent.dwMousePosition.X, irInBuf[i].Event.MouseEvent.dwMousePosition.Y);
                                SetConsoleTitle(message);
                        }
                    }


                    //=============================================
                    //
                    //
                    // Draw * at current cursor position AND update lastMousePosition if appropriate
                    //
                    if (!(irInBuf[i].Event.MouseEvent.dwEventFlags & MOUSE_WHEELED))
                    {
                        FillConsoleOutputCharacter(curBuf, '*', 1, irInBuf[i].Event.MouseEvent.dwMousePosition, &numCharsSet);
                        lastMousePosition = irInBuf[i].Event.MouseEvent.dwMousePosition;
                    }
                    else
                        FillConsoleOutputCharacter(curBuf, '*', 1, lastMousePosition, &numCharsSet);


                    //=============================================
                    //
                    //
                    // update the last*State variables
                    //
                    lastLeftState = irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED;
                    lastRightState = irInBuf[i].Event.MouseEvent.dwButtonState & RIGHTMOST_BUTTON_PRESSED;
                    lastMiddleState = irInBuf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED;
                    lastButtonState = irInBuf[i].Event.MouseEvent.dwButtonState;

                break;  // MOUSE_EVENT

            default:
                // MyErrorExit("unknown event type");
                break;
        }
    }
 }
 return 0;
}
I'm going to post back once I integrate this into moving a character up and down in the console window :).

-Max
Post Reply