Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for my binary to react to some global hotkeys in Linux?

Tags:

c

linux

hotkeys

Is it possible to listen for a certain hotkey (e.g:Ctrl-I) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?

EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say Ctrl-+, Ctrl and +) you could execute that action when you press the keys. If I would map Ctrl-+ to the volume increase action, each time I press ctrl-+ the volume should increase by a certain amount.

Thanks

like image 924
Vhaerun Avatar asked Sep 14 '25 18:09

Vhaerun


2 Answers

How global do your hotkeys need to be? Is it enough for them to be global for a X session? In that case you should be able to open an Xlib connection and listen for the events you need.

Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled. Clearly this is not what we want. We need to process the event before any other window can get to it. We need to call XGrabKey on the root window with the keycode and modifiers of our hotkey to accomplish this.

I found a good example here.

like image 56
Lawrence D'Anna Avatar answered Sep 17 '25 09:09

Lawrence D'Anna


I think smoofra is on the right track here; you're looking to register a global hotkey with X so that you can intercept keypresses and take appropriate action. Xlib is probably what you want, and XGrabKey is the function, i think.

It's not easy to learn, I'm afraid; I did locate this example that seems useful: TinyWM. I also found an example using Java/JNI (accessing the same underlying Xlib function).

like image 38
zweiterlinde Avatar answered Sep 17 '25 08:09

zweiterlinde