使用 ncurses 创建一个函数来检查 unix 中的按键 [英] Create a function to check for key press in unix using ncurses
问题描述
我一直在寻找与 kbhit() 等效的方法,并且我已经阅读了几个关于此主题的论坛,大多数似乎都建议使用 ncurses.
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.
我应该如何使用 ncurses 检查是否在 C++ 中按下了某个键.
How should I go about checking if a key is pressed in c++ using ncurses.
ncurses 提供的函数 getch() 从窗口读取字符.我想写一个函数,只检查是否有按键按下,然后我想做 getch().
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().
提前致谢.
推荐答案
你可以使用 nodelay()
函数将 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
", getch());
refresh();
} else {
printw("No key pressed yet...
");
refresh();
sleep(1);
}
}
}
这篇关于使用 ncurses 创建一个函数来检查 unix 中的按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!