How to detect when the delete key is pressed on the keyboard?

夙愿已清 提交于 2019-12-08 11:42:30

问题


I want that when the Del key is pressed a certain function is called. How can I achieve that using getch() if possible or otherwise some nested getch() calls?


回答1:


The function _getch() returns an "escaped" value for cursor and page control keys. For the keypad and the function keys, that is 0 followed by the key code, for other keys it is 224 followed by the key code.

#include <stdio.h>
#include <conio.h>

#define ESC     27
#define ESC1    0
#define ESC2    224

int main()
{
    int d=-1, e=-1;
    printf("Press a key (Esc to quit)\n");
    do {
        d = _getch();  
        if (d == ESC1) {
            e = _getch();  
            printf("%d %d\n", d, e);
        } else if (d == ESC2) {
            e = _getch();  
            printf("%d %d\n", d, e);
        } else {
            printf("%d\n", d);
        }
    } while (d != ESC);
    return 0;
}

Running the program and pressing three keys Delete, Del(keypad), Esc produces the output

Press a key (Esc to quit)
224 83
0 83
27

Of course, Numlock must be Off.




回答2:


You should look for this function kbhit() .It is basically for keyboard hit and look for del key ascii code and match with that .



来源:https://stackoverflow.com/questions/34451998/how-to-detect-when-the-delete-key-is-pressed-on-the-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!