Configure key repeat delay to detect if key is being pressed

前端 未结 2 1159
春和景丽
春和景丽 2021-01-14 11:46

I am writing a program in C that uses ncurses to check if a key is being pressed. The problem is that there is a key repeat delay.

If I for example hold the key \'a\

2条回答
  •  星月不相逢
    2021-01-14 12:07

    With ncurses (any curses implementation), you would use getch rather than getchar. The latter is a C standard I/O input function.

    Someone suggested Create a function to check for key press in unix using ncurses, which contains an answer worth mentioning. It uses nodelay to eliminate the time normally spent in getch for successive bytes of an escape sequence. In curses, you always have a tradeoff between waiting or not, since an escape sequence may not arrive all in one read operation. The example shown there reports cases when no character is available, and pauses (sleeps) for a short time in that case.

    If you only want to see the characters which are read, you could eliminate that pause (but making your program use a lot of CPU time):

    #include 
    
    int kbhit(void)
    {
        int ch = getch();
    
        if (ch != ERR) {
            ungetch(ch);
            return 1;
        } else {
            return 0;
        }
    }
    
    int main(void)
    {
        initscr();
    
        cbreak();
        noecho();
        nodelay(stdscr, TRUE);
    
        scrollok(stdscr, TRUE);
        while (1) {
            if (kbhit()) {
                printw("Key pressed! It was: %d\n", getch());
            }
        }
    }
    

    or (recognizing that there is a tradeoff), use napms to pause a short amount of time, but lessening the CPU time used:

    #include 
    
    int kbhit(void)
    {
        int ch = getch();
    
        if (ch != ERR) {
            ungetch(ch);
            return 1;
        } else {
            return 0;
        }
    }
    
    int main(void)
    {
        initscr();
    
        cbreak();
        noecho();
        nodelay(stdscr, TRUE);
    
        scrollok(stdscr, TRUE);
        while (1) {
            if (kbhit()) {
                printw("Key pressed! It was: %d\n", getch());
            } else {
                napms(20);
            }
        }
    }
    

提交回复
热议问题