这样做是正确的方法是使用Xlib。使用这个库,你可以这样写代码:
从一个例子摘自:here
while (1) {
XNextEvent(dis, &report);
switch (report.type) {
case KeyPress:
if (XLookupKeysym(&report.xkey, 0) == XK_space) {
fprintf (stdout, "The space bar was pressed.\n");
}
break;
}
}
/*This event loop is rather simple. It only checks for an expose event. XNextEvent waits for an event to occur. You can use other methods to get events, which are documented in the manual page for XNextEvent.*/
/*Now you will learn how to check if an event is a certain key being pressed. The first step is to put case KeyPress: in your switch for report.type. Place it in a similar manner as case Expose.*/
你也可以在映射到键盘的专用设备文件中使用poll或select。在我的情况是/dev/input/event1
。
如果您对映射到keyborad的特殊文件有什么疑问,请阅读文件/var/log/Xorg.0.log
(搜索单词keyboard
)。
在这里你有兴趣另一个链接:Linux keyboard event capturing /dev/inputX
目前还不清楚,你想分配几个“热键”组合到后台应用程序(其中的每一个会做一个特定的操作或将其聚焦)或者您是否需要能够将长输入输入到后台应用程序中,同时还能将相同的输入传递给当前关注的任何内容?第一种情况可以通过使用XCB(xcb_grab_key)来实现,这是实现这些目标的常规方式,而第二种情况对我来说没有多大意义。 – resistor