mouse.c

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#if 0
CMD="gcc -ansi -pedantic -Wall -Werror $0 -L/usr/X11R6/lib -lX11 -lcurses"
echo "$CMD"
exec $CMD
#endif

/***
 * C program to display mouse cursor location under the X Window System
 * by Shane Beasley (sbeasley@eecs.uic.edu)
 *
 * Requires the Unix Curses library + Xlib
 ***/

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <X11/Xlib.h>

int main (int argc, char *argv[]) {
  enum { escape = 27 };
  struct Point { int x, y; } last = { INT_MAX, INT_MAX };
  Display *x_server;
  Window root_window;

  if (!(x_server = XOpenDisplay(0))) {
    fputs("Could not open display.\n", stderr);
    exit(EXIT_FAILURE);
  }

  root_window = RootWindow(x_server, 0);
  initscr();
  noecho();
  nodelay(stdscr, 1);

  while (getch() != escape) {
    union { Window w; unsigned int u; int i; } unused;
    struct Point p;

    if (XQueryPointer(x_server, root_window, &unused.w, &unused.w, &p.x, &p.y,
		      &unused.i, &unused.i, &unused.u)
	&& (p.x != last.x || p.y != last.y)) {
      mvprintw(0, 0, "x=%-4d y=%-4d\n", p.x, p.y);
      last = p;
    }
  }

  endwin();
  XCloseDisplay(x_server);
  return 0;
}