Detect Keystrokes in a SFML App C++
Sanyam Sharma 221910304042
Posted on May 8, 2021
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;
}
}
}
}
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.
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;
This prints all the entered keystrokes(the ones that count as characters) onto the console.
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;
}
}
}
}
Posted on May 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024