我一直在寻找类似的东西,kbhit()
并且我已经阅读了几个关于这个主题的论坛,大多数人似乎都建议使用 ncurses。
我应该如何使用 ncurses 检查是否在 C++ 中按下了某个键?
ncurses 提供的函数getch()
从窗口中读取一个字符。我想编写一个只检查是否有按键然后我想做的函数getch()
。
我一直在寻找类似的东西,kbhit()
并且我已经阅读了几个关于这个主题的论坛,大多数人似乎都建议使用 ncurses。
我应该如何使用 ncurses 检查是否在 C++ 中按下了某个键?
ncurses 提供的函数getch()
从窗口中读取一个字符。我想编写一个只检查是否有按键然后我想做的函数getch()
。
您可以使用该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);
}
}
}