3

I want to execute code when user will use mouse wheel. I wrote simple example application and it is not working. Why my application is not reacting on mouse wheel?

#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
   Display *d;
   Window w;
   XEvent e;
   char *msg = "Hello, World!";
   int s;

   d = XOpenDisplay(NULL);
   if (d == NULL) {
      fprintf(stderr, "Cannot open display\n");
      exit(1);
   }

   s = DefaultScreen(d);
   w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1,
                           BlackPixel(d, s), WhitePixel(d, s));
    XSelectInput(d, w, ExposureMask | ButtonPressMask);
   XMapWindow(d, w);

   while (1) {
      XNextEvent(d, &e);
      if (e.type == Expose) {
         XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
         XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg));
      }
      if (e.type == ButtonPress){
        switch (e.xbutton.button){
            case Button4:
                printf("Scrolled up");
                break;
            case Button5:
                printf("Scrolled down");
                break;
            default:
                printf("cos");
        }
      }
   }

   XCloseDisplay(d);
   return 0;
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
BPS
  • 945
  • 1
  • 16
  • 35
  • Does it react to any mouse button press? How do you know `Button4` and `Button5` correspond to the scroll wheel? – yano Sep 02 '16 at 18:33

1 Answers1

4

your code is correct, the reason you don't see results immediately is because fprintf buffers data until newline. Replace your debug lines with something like printf("Scrolled up\n"); and you'll see results immediately. Alternatively you might do setbuf(stdout, NULL); to disable buffering.

See this related SO question: Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
Andrey Sidorov
  • 22,962
  • 4
  • 58
  • 73