Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to get keyboard key press value (or number/code) [duplicate]

Tags:

c++

I want to see which key is pressed by user.

I know there is cin() or getline(cin, var) but I don't want an input, I want to get the number of the key(index, or code it is called?).

For instance, I want to get if the user has pressed F1 or F10 or Enter or Escape and then in return do something proper.

For instance:

if(user_has_pressed_escape)
{
 exit_the_console();
}
like image 729
Mostafa Talebi Avatar asked Dec 26 '22 07:12

Mostafa Talebi


2 Answers

This is available via the OS own API. Different OSes have different APIs (for instance android does not have a F10 key at all).

Often you will use a third party library to wrap the API so you can code independent from the OS. There are a lot of choices when it comes to a 3rd party library: SDL, QT, wxWidgets, GTK and many many more..

These libraries hide the interaction with the specific OS API from you and let you code once and run on many types of systems. But to understand how it works under the hood you might look at each OS documentation.

For instance on Windows GetKeyboardState or PeekMessage

On Linux X11: XQueryKeymap or via XPeekEvent

like image 183
odedsh Avatar answered Jan 30 '23 07:01

odedsh


You can easily get event of ESC key down using ASCII table https://en.wikipedia.org/wiki/ASCII

if (27 == getchar()) // 27 is for ESC
{
    //do something
}

Function keys (F1, F2, ...) depend on your OS.

like image 30
Dakorn Avatar answered Jan 30 '23 07:01

Dakorn