简体   繁体   English

处理SDL和C ++中的关键事件

[英]Handling key events in SDL and C++

I'm in the process of migrating a program from GLUT to SDL. 我正在将程序从GLUT迁移到SDL。 In my current program pressing the a key results in a different response then pressing the A key. 在我当前的程序中,按a键会产生不同的响应,然后按A键。 This was pretty straightforward to do in GLUT as it the keyboard function callback passed in the ASCII value of the key that was pressed. 这在GLUT中非常简单,因为键盘函数回调在按下的键的ASCII值中传递。

void keyPressedFn(unsigned char key, int x, int y){
    switch(key){
    case 'a':
    // do work for a
    break;
    case 'A':
    // do work for A
    break;
    }
}

I'm struggling to replicate similar functionality in SDL as pressing the a key produces the same response regardless of if SHIFT or CAPS LOCK are pressed as well. 我正在努力在SDL中复制类似的功能,因为按下a键会产生相同的响应,无论是否按下SHIFT或CAPS LOCK。

Is there a simple way of replicating the above function in SDL? 有没有一种简单的方法在SDL中复制上述功能?

Edit : In the example above I only show how to handle one key, in practice however, I am going to have a list of about 15 keys that I want to respond to differently if the shift key is pressed as well. 编辑 :在上面的例子中我只展示了如何处理一个键,但实际上,我将有一个大约15个键的列表,如果按下shift键,我想要以不同的方式响应。

Check the keyboard modifiers that are present when you get a keydown event. 检查keydown事件时出现的键盘修饰符。 For example: 例如:

while(SDL_PollEvent(&event))
{
  switch(event.type)
  {
  case SDL_KEYDOWN:
    if(event.key.keysym.sym == SDLK_a)
    {
      if(event.key.keysym.mod & KMOD_SHIFT)
      {
        // Handle 'A'
      }
      else
      {
        // Handle 'a'
      }
    }
    break;

  ...

  }
}

SDL_keysym has mod field, which contains state of modifier keys at the time the event has been emitted. SDL_keysym具有mod字段,其中包含发出事件时修改键的状态。 Bit-AND it with KMOD_SHIFT to check whether Shift has been active. 使用KMOD_SHIFT进行位 - 并检查Shift是否已激活。 See SDL wiki . 请参阅SDL wiki

Why not just do this? 为什么不这样做呢?

void keyPressedFn(unsigned char key, int x, int y){
    switch(key){
    case 'a':
    case 'A':
    // do work for A or a
    break;
    }
}

Do you have some other concerns that you cannot do as what I have suggested? 您是否还有其他一些我不建议的问题? If not I think this is as simple as it can get. 如果不是,我认为这很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM