tags:

views:

138

answers:

2

Hi, 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? :)

+3  A: 

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.

karlphillip
Thanks a lot dude! At last I used the XTst extension, I found it in xmacro's source code. You can find my implementation here: http://github.com/Aitjcize/Qwertickle/blob/master/src/qwertickle.c
Aitjcize
@Aitjcize: That's very nice code you've written. Your switch on the key pressed would be more readable if you used character literals: `case 65` can be `case 'A'` for example.
Matt Joiner
@karlphillip: A great answer, lots of links for further reading, well done.
Matt Joiner
A: 

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)

falloutboy
Reading /dev/input/event* doesn't work if X's evdev drive has it grabbed.
Burton Samograd