BulBul
BulBul

Reputation: 1209

SDL 2.0 Keyboard Handling

I am writing a very simple sample program that simply shows you "a key is pressed or not" only once, the key pressed event is triggered whenever i press any number of keys (either i press one key, two keys or more), while the key is released event is triggered when an SDL_KEYUP event is occurred while the number of keys pressed is only 1 key, this example works perfectly on arrow keys, however for the other keys whenever i press multiple keys and release only one of them a "Key is released" message is triggered followed by "a key is pressed", i failed to locate the problem with this.

my Code:

#include <iostream>
#include <SDL2/SDL.h>

using namespace std;
SDL_Event input;


int main(int argc, const char * argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);


int y = 0;
int z = 0;
int w = 0;
bool key = false;

const Uint8 *state = SDL_GetKeyboardState(NULL);


while (1){
   w = 0;
   SDL_PollEvent(&input);

  //check for events generated

   switch (input.type) {
       case SDL_KEYDOWN:  
           key = true;
           break;
           case SDL_KEYUP:
           key = false;
           break;

       default:
           break;
   }



  // Check for no. of keys pressed using ASCII code

    for (y = 48;y<=127;y++)
        if(state[y] == 1)
            w++;


   // Display the messages

   if (key && z==0 )
   {
       cout << "Key is Pressed" << endl;
       z = 1;
   }
   else if (!key && w < 1 && z==1)
   {
       cout << "Key is released" << endl;
       z = 0;

   }



}

return 0;
 }

Upvotes: 0

Views: 2723

Answers (1)

BulBul
BulBul

Reputation: 1209

The problem was with the initialization of the for loop, SDL 2 does not use the same ASCII enumerations for characters thus my code tend to ignore the code enumerations outside the (48-127) range after changing the code to:

for (y = 0;y<=127;y++)
if(state[y] == 1)
        w++;

the problem is solved

Upvotes: 1

Related Questions