How to capture a "down" "up" event for a key or mouse button press in C

I have found many examples that either use X11

, or linux/input.h

unfortunately I am on Cygwin where linux/input.h

none exists.

I need a simple example that I can use to detect events like:

  • Down key
  • Key


  • Mouse button down
  • Mouse up button

I would like to find a solution that can work on Cygwin / Linux and optionally on Windows / OSX.

Is it possible?

So far I have found one solution using X11:

#include <stdio.h>
#include <X11/Xlib.h>

char *key_name[] = {
    "second (or middle)",
    "fourth",  // :D
    "fivth"    // :|

int main(int argc, char **argv)
    Display *display;
    XEvent xevent;
    Window window;

    if( (display = XOpenDisplay(NULL)) == NULL )
        return -1;

    window = DefaultRootWindow(display);
    XAllowEvents(display, AsyncBoth, CurrentTime);

                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask , 

    while(1) {
        XNextEvent(display, &xevent);
        switch (xevent.type) {
            case ButtonPress:
                printf("Button pressed  : %s\n", key_name[xevent.xbutton.button - 1]);
            case ButtonRelease:
                printf("Button released : %s\n", key_name[xevent.xbutton.button - 1]);

    return 0;


Creation with

gcc foo.c -lX11


Unfortunately, the Xserver must be running startxwin&

and the mouse pointer must be inside the X server window. So this is not a good decision.

Another approach was using ncurses, but it seems that states key-down

are key-up

not possible.

The example below does not work on cygwin because it is conio.h

not POSIX:

#include <stdio.h>
#include <conio.h>
char ch;
void main(){
        if(kbhit()){ //kbhit is 1 if a key has been pressed
            printf("pressed key was: %c", ch);


conio.h is a C header file used primarily by MS-DOS compilers to provide console I / O. [1] It is not part of the C or ISO C standard library, and is not defined by POSIX.


source to share

1 answer

You seem to want to create a cross platform program. I doubt that you can only solve this problem in Linux libraries. I suggest:

  • Ditch X in favor of Qt or GTK.
  • Create a module that listens for key events using tools from Windows.h

    compiled only if the user is on Windows. Sooner or later, you still have to do it because your project is growing.


All Articles