Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect the ESC key in C?

Tags:

c

i wrote a piece of code to detect arrow keys using _getch(); and i wish to detect the esc key as well but i dont actually know what are the numbers that i should use so any help is appreciated.

#include <conio.h>
#include <stdio.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77

int c = 0;
_getch();
switch ((c = _getch())) {
case KEY_UP:
    printf("Up\n");
    break;
case KEY_DOWN:
    printf("Down\n");
    break;
case KEY_LEFT:
    printf("Left\n");
    break;
case KEY_RIGHT:
    printf("Right\n");
    break;
default:
    printf("Null\n");
    break;

each of the arrow keys is a combination of two characters of ascii code 224 and the defined ones (notice the first _getch();) but i dont know that for the escape key, i tried searching but didnt find them, a full list of those would be so helpful.

Thanks.

like image 522
xixhxix Avatar asked Dec 02 '22 15:12

xixhxix


1 Answers

Up,Down,Left,Right is known as extended key and to detect them you have to read Two Char first one is Null and the second is the ASCII code but ESC is not extended key so you can detect it with only one char.

I hope that code will help you:

#include <stdio.h>
#include <stdlib.h>

#define esc 27

int main()
{
    char ch;
    do
    {
        ch = getch();
        switch(ch)
        {
            case esc:
                // your logic goes here
                break;
        }
    }
    while(exitflag != 1);
}
like image 116
Ahmed Lotfy Avatar answered Dec 28 '22 11:12

Ahmed Lotfy