Mim*_*ack 14 c++ unix command-line ncurses
我一直在寻找相当于kbhit()的东西,我已经阅读了几个关于这个主题的论坛,大多数人似乎建议使用ncurses.
我应该如何使用ncurses检查是否在c ++中按下了某个键.
ncurses提供的函数getch()从窗口中读取字符.我想编写一个函数,只检查是否有按键然后我想做getch().
提前致谢.
Mat*_*ery 20
您可以使用该nodelay()功能转换getch()为非阻塞呼叫,ERR如果没有按键可以返回.如果按键可用,它将从输入队列中拉出,但如果您愿意,可以将其推回队列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);
}
}
}
Run Code Online (Sandbox Code Playgroud)