且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建一个函数来检查unix中使用ncurses的按键

更新时间:2022-05-23 06:33:31

您可以使用 nodelay()函数$ c> getch()转换为非阻塞调用,如果没有按键可用则返回 ERR 。如果按键可用,它将从输入队列中拉出,但如果您喜欢 ungetch(),您可以将其推回队列。

You can use the nodelay() function to turn getch() into a non-blocking call, which returns ERR if no key-press is available. If a key-press is available, it is pulled from the input queue, but you can push it back onto the queue if you like with ungetch().

#include <ncurses.h>
#include <unistd.h>  /* only for sleep() */

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());
            refresh();
        } else {
            printw("No key pressed yet...\n");
            refresh();
            sleep(1);
        }
    }
}