C++ Detect When User Presses Arrow Key

C++ Detect when user presses arrow key

#include <conio.h>
#include <iostream>
using namespace std;

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77

int main()
{
int c = 0;
while(1)
{
c = 0;

switch((c=getch())) {
case KEY_UP:
cout << endl << "Up" << endl;//key up
break;
case KEY_DOWN:
cout << endl << "Down" << endl; // key down
break;
case KEY_LEFT:
cout << endl << "Left" << endl; // key left
break;
case KEY_RIGHT:
cout << endl << "Right" << endl; // key right
break;
default:
cout << endl << "null" << endl; // not arrow
break;
}

}

return 0;
}

output like this:

Up

Down

Right

Left

Up

Left

Right

Right

Up

detected arrow key press!

C++ — Arrow key press detection with getch() prints some words inexplicably

When reading keys with conio and getch, in order to be able to handle special keys (arrow keys, function keys) while still fitting its return value in a char, getch returns special keys as two-char sequences. The first call returns 0, while the second call returns the code of the special key. (Otherwise, your KEY_DOWN - ASCII 80 - by itself would be 'P'.)

MSDN has more info.

One approach to putting all of this together would be something like the following:

char c = getch();
if (c == 0) {
switch(getch()) {
// special KEY_ handling here
case KEY_UP:
break;
}
} else {
switch(c) {
// normal character handling
case 'a':
break;
}
}

getch and arrow codes

By pressing one arrow key getch will push three values into the buffer:

  • '\033'
  • '['
  • 'A', 'B', 'C' or 'D'

So the code will be something like this:

if (getch() == '\033') { // if the first value is esc
getch(); // skip the [
switch(getch()) { // the real value
case 'A':
// code for arrow up
break;
case 'B':
// code for arrow down
break;
case 'C':
// code for arrow right
break;
case 'D':
// code for arrow left
break;
}
}

How to detect combined key input in C++?

Even if conio.h function are rather low level, they are not low enough for what you want: you do not want to extract characters from a console buffer (what getch does) but know the state (pressed/released) of some keys.

So you should directly use the WINAPI function GetKeyState. Your program will no longer be MS/DOS compatible, but I do not think that is is a real question in 2020...

gtkmm: How to detect arrow key is pressed

If you change

this->signal_key_press_event().connect(
sigc::mem_fun(*this, &MyWindow::onKeyPress));

to

this->signal_key_press_event().connect(
sigc::mem_fun(*this, &MyWindow::onKeyPress), false);

your signal handler should receive the events. That false argument is for the after flag. It is true by default, meaning that other signal handlers may intercept the signal before MyWindow::onKeyPress, since it is the last one.



Related Topics



Leave a reply



Submit