如何正确处理SDL2中的控制键组合 [英] How to correctly handle control-key combinations in SDL2
问题描述
在基于 SDL 2.0 的应用程序中,我想同时处理Control +
和Control =
.
In my SDL 2.0 based application, I would like to handle both Control +
and Control =
.
我知道我可以处理SDL_KEYDOWN
事件,并结合KEYMODE_CTRL
查找SDLK_EQUALS
密钥代码.甚至检查KEYMOD_SHIFT' to distinguish between
+ and
=`.但是,这不是便携式的,并且在将这些符号映射到不同键的键盘上会损坏.
I understand that I could handle the SDL_KEYDOWN
event and look for the SDLK_EQUALS
keycode in combination with KEYMODE_CTRL
. And even check for KEYMOD_SHIFT' to distinguish between
+and
=`. However, this is not portable and breaks on keyboards where those symbols are mapped to different keys.
我尝试过的另一件事是启用SDL_StartTextInput()
,然后侦听SDL_TEXTINPUT
事件.但是,这仅适用于可打印字符.它完全忽略了控制序列.
Another thing I have tried is to enable SDL_StartTextInput()
and then listen to SDL_TEXTINPUT
events. However that only works for printable characters. It ignores control sequences completely.
正确的方法是什么?我看到 SDL 1.2 实际上在SDL_Keysym
结构中有一个unicode
字段.那绝对会让我容易得多.有谁知道为什么要删除它,以及 SDL 2.0 中的等效内容是什么?
What is the correct the way to do this? I see SDL 1.2 actually had a unicode
field in the SDL_Keysym
structure. That would definitely make this a lot easier for me. Does anyone know why that was removed and what the equivalent in SDL 2.0 would be?
推荐答案
下面是一个示例,您如何将unicode输入作为SDL_TEXTINPUT获得,而将其余部分作为SDL_KEYDOWN获得:
Here is an example how you can get unicode input as SDL_TEXTINPUT but the rest as SDL_KEYDOWN:
#include "SDL.h"
int main(int argc, char *argv[]) {
int done = 0;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *w = SDL_CreateWindow("foo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
640, 480, 0);
int lctrl = 0, rctrl = 0;
SDL_StartTextInput();
while (!done) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
done = 1;
break;
case SDL_TEXTINPUT: {
int ctrl_state = lctrl || rctrl;
printf("%s, ctrl %s\n", event.text.text, (ctrl_state) ? "pressed" : "released");
} break;
case SDL_KEYDOWN:
if(event.key.keysym.sym == SDLK_RCTRL) { rctrl = 1; }
else if(event.key.keysym.sym == SDLK_LCTRL) { lctrl = 1; }
break;
case SDL_KEYUP:
if(event.key.keysym.sym == SDLK_RCTRL) { rctrl = 0; }
else if(event.key.keysym.sym == SDLK_LCTRL) { lctrl = 0; }
break;
}
}
SDL_UpdateWindowSurface(w);
}
SDL_Quit();
return 0;
}
为简化起见,它忽略了SDL_TEXTEDITING,它可能是(也可能不是)您想要的.也可以使用SDL_GetKeyboardState
代替手动处理事件和累积修饰键标志,从而得到相同的结果.
To simplify things, it ignores SDL_TEXTEDITING, which may (or not) be what you want. Also SDL_GetKeyboardState
can be used instead of manually processing events and accumulating modifier keys flags, with the same result.
这篇关于如何正确处理SDL2中的控制键组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!