开发者

Handling key events in SDL and C++

I'm in the process of migrating a program from GLUT to SDL. In my current program pressing the a key results in a different response then pressing the A key. 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.

void keyPressedFn(uns开发者_开发问答igned 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.

Is there a simple way of replicating the above function in 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.


Check the keyboard modifiers that are present when you get a keydown event. 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. Bit-AND it with KMOD_SHIFT to check whether Shift has been active. See 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜