Aitjcize
Aitjcize

Reputation: 187

How to grab 'key-press-event' when the window is not focused?

I am writing a program using gtk. What the program does is monitor the keystroke the user entered and play a sound. My question is that how do I catch the key-press-event when the window is not focused? I'm planning to let my program stay in tray icon, so I wonder how I can grab any key-press-event from there. Thanks

Edit: I finally find a way to do it - The XTest extension, I found the a piece of code snippet from the program 'xmacro'. You can see my implementation here: http://github.com/Aitjcize/Qwertickle/blob/master/src/qwertickle.c

btw, it's still quite buggy, maybe someone can help me out? :)

Upvotes: 4

Views: 2188

Answers (2)

derhoch
derhoch

Reputation: 458

There is a program called xbindkeys that can bind mouse and keyboard keys in X to launch shell commands. You can either utilize this to send commands to your program, or look at the sourcecode to see how its done: xbindkeys

You can also directly open /dev/input/eventX and read() from it to an input_event struct, but thats a little nasty, because you need to have the proper rights (normally root, or change it with chmod)

Upvotes: 0

karlphillip
karlphillip

Reputation: 93410

As Matt Joiner said,

This kind of thing isn't as easy in Linux.

and unfortunately GTK+ can't do this kind of magic.

You should take a look at XEvIE - X Event Interception Extension - it will make your job easier.

XEvIE is a X extension providing functionalities to allow users intercept keyboard/mouse events.

And as suggested by this guy, another way to go would be to use XGrabKey()/XUngrabKey() from X11. I believe that tinywm shows how to use it correctly.

Upvotes: 3

Related Questions