Thijser
Thijser

Reputation: 2633

c++ ubuntu detecting real time keypress event

I'm writing a program that needs to respond towards a key press (say by printing "hello key press") in real time (the program runs in a giant loop that takes around 2 seconds to complete). I have found one potential answer Detecting keydown and keyup events on Linux C++ but the answers weren't very clear to me (I also looked into the 4 answer that are linked via duplicates). Can somebody please provide a simple code example of how to make a linux program respond towards a keypress by printing a single line (or doing whatever) without having to check for it each loop?

Upvotes: 2

Views: 3548

Answers (2)

doron
doron

Reputation: 28892

Take a look at SDL Input events. Simple DirectMedia Layer (SDL) provides a cross platform API developed for things like gaming. It does provide a lot of low level keyboard, mouse etc functionality. A link can be found here.

Upvotes: 3

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

There are essentially to ways:

If the long loop is long in time, but short in code (that is: it contains another working inner loop that keeps all the time) you can place a event presence check in the most inner loop.

If you cannot rework the long loop, you have most likely to split the application in two distinct threads: one performing event detection and immediate actions, and another one to which to delegate the lengthy operations.

Upvotes: 1

Related Questions