August 10, 2010

XServer Event Handling C Example

« Caching Example with Spring Annotations and Ehcache | Main | How to get all window events at GNOME environment »

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:

Posted by rafael.sobek at 4:40 AM in Linux

 

[Trackback URL for this entry]

Comment: gaurav at Sa, 15 Jan 2:38 PM

good and well managed code
helpful tome
thank you

Comment: Helloooooo at Mi, 15 Jun 11:01 AM

thanks Nice Example

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« August »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
293031