DEV Community

Sanyam Sharma 221910304042
Sanyam Sharma 221910304042

Posted on

Detect Keystrokes in a SFML App C++

SFML(Simple and Fast Multimedia Library) provides a simple interface to the various components of your PC, to ease the development of games and multimedia applications.

This article assumes that you have SFML configured and know how to compile and run it

Rendering a new window:

#include<SFML/Graphics.hpp>
#include<iostream>

int main(){

    sf::RenderWindow window(sf::VideoMode(600, 600), "Sample SFML App");

    while (window.isOpen()){ 

        sf::Event event;
        while (window.pollEvent(event)){

            switch (event.type)
            {

                case sf::Event::Closed:
                    window.close();
                    break;

            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This has now rendered a window of 600px height and 600px width and with the title "Sample SFML App".
The windows.isOpen() lets us stop the window from closing automatically and perform operations on it, and event can be used to detect things happening in the Window. Also we have used a switch case which can be further used to do things when a certain operation takes place on the window.

For example when the "Close" button is pressed on the title bar, the window closes, we can also make it print something, etc.

Alt Text

Now all we need to do is create another case where we will detect any text entered. We will do that by implementing sf::Event::TextEntered as a second case.

case sf::Event::TextEntered:

                    if(event.text.unicode<128){
                        std::cout<<(char)event.text.unicode<<"\n";
                    }
                    break;
Enter fullscreen mode Exit fullscreen mode

This prints all the entered keystrokes(the ones that count as characters) onto the console.

Alt Text

Full code:

#include<SFML/Graphics.hpp>
#include<iostream>

int main(){

    sf::RenderWindow window(sf::VideoMode(600, 600), "Sample SFML App");

    while (window.isOpen()){ 

        sf::Event event;
        while (window.pollEvent(event)){

            switch (event.type)
            {

                case sf::Event::Closed:
                    window.close();
                    break;

                case sf::Event::TextEntered:

                    if(event.text.unicode<128){
                        std::cout<<(char)event.text.unicode<<"\n";
                    }
                    break;
            }
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)