Using ncurses to capture mouse clicks on a console application

Pedro Cori picture Pedro Cori · Jul 3, 2012 · Viewed 10.3k times · Source

I'm making a console application for unix platforms, and I'm using the curses (or ncurses) library to handle keyboard and mouse input. The problem is that I've found very little documentation on how exactly to use it for that, appart from this page and this one, which don't have very detailed examples. I've managed to capture the left click, but I can't get it to work for the right click because the options menu for the terminal emulator appears at the cursor location, but the event is not processed by the application. How can I avoid this and have the event captured in the application?

I have the following line for the configuration of mouse events:

// Set up mouse event throwing
mousemask(BUTTON1_PRESSED | BUTTON2_PRESSED, NULL);

And in the method that processes input, I have the following:

int c = getch();
MEVENT event;
switch(c)
{
    case KEY_UP:
        ... do stuff
        break;
    case KEY_DOWN:
        ... do stuff
        break;
    case KEY_MOUSE:
        if(getmouse(&event) == OK)
        {
            if(event.bstate & BUTTON1_PRESSED) // This works for left-click
            {
                ... do stuff
            }
            else if(event.bstate & BUTTON2_PRESSED) // This doesn't capture right-click
            {
                ... do other stuff
            }
            else
                fprintf(stderr, "Event: %i", event.bstate); // Doesn't print anything on right-click
        }
        break;
    default:
        return;
}

I've also tried configuring mousemask() with the ALL_MOUSE_EVENTS mask, but it still doesn't print any events on the last else clause, so I figure the event simply isn't triggering. Any help on this would be much appreciated.

Answer

Designation picture Designation · Dec 14, 2012

For anyone else coming here trying to figure out why s/he can't capture mouse events at all with Ncurses, most likely this is the line that you need:

keypad(window, TRUE);      

Without this, I didn't get any mouse events with getch().

It's missing from all the tutorials/examples I've seen, that's why it took me a lot of time to figure out what was wrong with my code - maybe this answer will help others find the solution faster than I did.