SFML Keyboard event handling without RenderWindow

Apr 3, 2014 at 10:48am
I'm currently doing basic event handling in the console using SFML.

The problem with my code below is when i pressed either one of UP,DOWN,R,L
It executes the specified statement somewhat like a hundred times LOL :DD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <SFML/Window/Keyboard.hpp>

int main()
{
    using sf::Keyboard;

    while( 1 ) { // <== probably a bad way
        if( Keyboard::isKeyPressed( Keyboard::Escape ) )
            break;
        else if( Keyboard::isKeyPressed( Keyboard::Left ) )
            std::cout << "Left Key pressed\n";
        else if( Keyboard::isKeyPressed( Keyboard::Right ) )
            std::cout << "Right key pressed\n";
        else if( Keyboard::isKeyPressed( Keyboard::Up ) )
            std::cout << "Up key pressed\n";
        else if( Keyboard::isKeyPressed( Keyboard::Down ) )
            std::cout << "Down key pressed\n";
    }
}


Example output, when i pressed the up key :

Up key pressed
Up key pressed
Up key pressed
Up key pressed
Up key pressed
Up key pressed
Up key pressed
// and so on
Apr 3, 2014 at 12:36pm
So you want some sort of single press?

Not sure if SFML has a function that supports that. I guess you could do something like this, though:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <SFML/Window/Keyboard.hpp>

int main(int argc, const char* argv[])
{
   const int MAX_KEYS = 4;
   bool keyPressed[MAX_KEYS];

   enum keys
   {
      left,
      right,
      up,
      down
   };

   for (int i = 0; i < MAX_KEYS; ++i)
   {
      keyPressed[i] = false;
   }

   while (1)
   {
      /* For each key, I'll use left as an example */
      if(Keyboard::isKeyPressed(Keyboard::Left))
      {
          if (!keyPressed[left])
          {
             std::cout << "Left Key pressed\n";
             keyPressed[left] = true;
          }
      }
      else
      {
          keyPressed[left] = false;
      }
   }
}


Quick untested example as I'm at work an on my lunch break. There's definitely a more elegant way to do this, too. For example, you could map the keys to bools an iterate over the keys in the map. That way, you wouldn't need to write out a case for each key.

Hope this helps.
Last edited on Apr 3, 2014 at 12:40pm
Apr 4, 2014 at 11:36pm
SFML provides a flag in sf::RenderWindow that allows you to set the key repeat options. sf::RenderWindow::setKeyRepeat();
http://www.sfml-dev.org/documentation/2.1/classsf_1_1Window.php#aef9f2b14c10ecba8a8df95dd51c5bb73
Apr 5, 2014 at 8:13am
many tnx @iHutch105, it worked !!, tnx also @CodeGazer, i didn't knew that method exists, although i'm only testing this in the console, i can possibly use that method for a future project
Topic archived. No new replies allowed.