C++ 使用 ncurses 创建一个函数来检查 unix 中的按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4025891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a function to check for key press in unix using ncurses
提问by Mimsy Hyman
I have been looking for an equivalent to kbhit() and I have read several forums on this subject, and the majority seems to suggest using ncurses.
我一直在寻找与 kbhit() 等效的方法,并且我已经阅读了几个关于这个主题的论坛,大多数似乎都建议使用 ncurses。
How should I go about checking if a key is pressed in c++ using ncurses.
我应该如何检查是否使用 ncurses 在 C++ 中按下了某个键。
The function getch() provided by ncurses reads character from the window. I would like to write a function that only checks if there is a key press and then I want to do getch().
ncurses 提供的函数 getch() 从窗口读取字符。我想编写一个函数,只检查是否有按键按下,然后我想做 getch()。
Thanks in advance.
提前致谢。
回答by Matthew Slattery
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()
.
您可以使用该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);
}
}
}