[英]GDK signal, keypress, and key masks
I am trying to catch user key press Ctrl+d on a GUI window to quit. 我试图捕获用户键在GUI窗口上按Ctrl + d退出。 My code looks like this:
我的代码看起来像这样:
static gboolean
callback(GtkWidget *widget,
GdkEventKey *event,
gpointer data)
{
if(event->state == GDK_CONTROL_MASK && event->keyval == 'd')
gtk_main_quit();
return FASLE;
}
This works on my laptop(Ubuntu 11.04, gcc 4.5.2, libgtk 2.24.4). 这适用于我的笔记本电脑(Ubuntu 11.04,gcc 4.5.2,libgtk 2.24.4)。 But when I do the same thing on a newer system(Ubuntu 12.10, gcc 4.7.2, libgtk 2.24.13), it doesn't work.
但是当我在一个较新的系统(Ubuntu 12.10,gcc 4.7.2,libgtk 2.24.13)上做同样的事情时,它不起作用。
I added g_print("%u\\n", event->state);
我添加了
g_print("%u\\n", event->state);
before the if
statement, it shows that when I press Ctrl
, the event->state
is 20 instead of 4 or 1 << 2 in the documentation. 在
if
语句之前,它显示当我按下Ctrl
,文档中的event->state
为20而不是4或1 << 2。 If I change the GDK_CONTROL_MASK
to 20, it works on the newer system but not the old one. 如果我将
GDK_CONTROL_MASK
更改为20,它适用于较新的系统,但不适用于较旧的系统。 Someone please tell me why this happen and how to fix it. 有人请告诉我为什么会发生这种情况以及如何解决这个问题。
event->state
is a bitmap , which means that a value of 20 doesn't mean "20 instead of 4", but "4 and 16 at the same time". event->state
是一个位图 ,这意味着值20不表示“20而不是4”,而是“4和16同时”。 According to the headers, the value 16 ( 1 << 4
) corresponds to the MOD2
modifier, which might correspond to the fn key present on laptops. 根据标题,值16(
1 << 4
)对应于MOD2
修饰符,其可能对应于笔记本电脑上存在的fn键。
A simple fix is to use the &
operator to check for control while ignoring other modifiers: 一个简单的解决方法是使用
&
运算符来检查控件,同时忽略其他修饰符:
if (event->state & GDK_CONTROL_MASK && event->keyval == 'd')
which will work on both systems. 这将适用于两个系统。
This happens because state
also includes modifiers like Caps Lock and Num Lock. 发生这种情况是因为
state
还包括Caps Lock和Num Lock等修饰符。
The solution is documented at https://developer.gnome.org/gtk3/stable/checklist-modifiers.html : 该解决方案记录在https://developer.gnome.org/gtk3/stable/checklist-modifiers.html :
Use gtk_accelerator_get_default_mod_mask()
to get a bitmap of the modifiers that are also accelerator keys (Control, Alt, Shift, Super, Hyper, and Meta), then bitwise and the event state, eg: 使用
gtk_accelerator_get_default_mod_mask()
获取修饰符的位图,这些修饰符也是加速键(Control,Alt,Shift,Super,Hyper和Meta),然后是按位和事件状态,例如:
GdkModifierType accel_mask = gtk_accelerator_get_default_mod_mask ();
if (event->state & accel_mask == GDK_CONTROL_MASK && event->keyval == 'd')
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.