The X Server or X Window System defines a basic graphical network protocol. It offers low-level drawing operations, window state (resize, change of position, ...) and keyboard or mouse input event handling. The following example describes in C code how to write a daemon, that process XServer keyboard and window focus events.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
//represenation of X display
static Display *dpy;
//represenation of X window
static Window focuswin = None;
static void attach_to_focuswin(void) {
fprintf(stdout, "func: attach_to_focuswin\n");
int revert_to = 0;
XGetInputFocus(dpy, &focuswin, &revert_to);
if (focuswin != None)
XSelectInput(dpy, focuswin, FocusChangeMask | KeyPressMask);
else
sleep(1);
}
static void handle_event(void) {
fprintf(stdout, "func: handle_event\n");
XEvent ev;
char buf[100];
int len;
//get current event of X display
XNextEvent(dpy, &ev);
if (ev.xany.type == FocusOut) {
focuswin = None;
fprintf(stdout, "func: handle_event -> focusing out of an window\n\n\n");
} else if (ev.xany.type == FocusIn) {
fprintf(stdout, "func: handle_event -> focusing out of an window\n\n\n");
} else if (ev.xany.type == KeyPress) {
len = XLookupString(&ev.xkey, buf, 99, 0, 0);
buf[len] = 0;
printf("%s", buf);
fflush(stdout);
} else {
fprintf(stdout, "func: handle_event -> something else %d\n\n\n", ev.type);
}
}
int main(void) {
//how to get xserver display
dpy = XOpenDisplay(getenv("DISPLAY"));
//if a display isn't exist
if (dpy == NULL) {
fprintf(stdout, "cannot init display\n");
exit(1);
}
//daemon loop
while (1) {
if (focuswin == None)
attach_to_focuswin();
else
handle_event();
}
}
Regards
Rafael Sobek
Technorati Tags: xserver event handling

good and well managed code
helpful tome
thank you