控制台应用程序中的输入事件循环
我正在尝试制作一个能够将击键作为事件处理的小型控制台应用程序。我需要的主要是能够获取击键并能够使用它们执行某些操作,而无需处理典型的标准输入读取功能。
我尝试检查像 mplayer 这样实现此功能的程序的代码(例如,用于停止播放),但我无法通过如此大的代码库了解其核心。
谢谢
I'm trying to make a little console application that is able to deal with keystrokes as events. What I need is mostly the ability to get the keystrokes and be able to do something with them without dealing with the typical stdin reading functions.
I tried to check the code of programs like mplayer, which implement this (for stopping the play, for example), but I can't get to the core of this with such a big code base.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 ncurses 系列函数 'getch',如链接所示,如下顺便说一句,另一个链接将对您有所帮助,应该指出的是,ncurses 是平台可移植的,所以如果你决定重新定位到另一个平台,你应该可以接受它,这是一个很大的优势......
You could use the ncurses family of functions 'getch' as shown in the link, here's another link that will be of help to you, by the way, it should be pointed out, ncurses is platform portable so you should be pretty ok with it if you decide to re-target to another platform which is a big plus...
在上述应用程序的核心,您会发现
select(2)
< /a>.只需针对 stdin 使用它即可确定何时可以从中读取输入。At the core of said applications you'll find
select(2)
. Just use it against stdin to find out when you can read input from it.查看您是否有权访问 getch() 函数。使用此函数,您可以检索单个击键,甚至 (CTRL+(char)) 击键。获得这些数据后,我想您只需为此事件创建一个处理程序即可。因此,您可以做的是实现一个索引/函数指针对表,使用击键作为索引,并为每个索引分配一个函数指针来处理该事件。希望这有帮助。
See if you have access to the getch() function. With this function you can retrieve a single keystroke, even (CTRL+(char)) keystrokes. After you have this data I suppose it's up to you to just create a handler for this event. So what you could do is implement a table of index/function ptr pairs, using the keystroke as an index, and assigning each index a function pointer to handle that event. Hope this helps.
要将 stdin 更改为在按下 Enter 之前不缓冲,您可以像这样乱搞终端 i/o 设置。
termios 结构以及 tcgetattr() 和 tcsetattr() 原型位于 termios.h 文件中。
然后你可以使用 select() 来检查一个字符是否准备好被读取。
To change stdin to not buffer until enter is hit, you can mess around with the terminal i/o settings like so..
The termios structure and the tcgetattr() and tcsetattr() prototypes are in the termios.h file.
Then you can use select() to check whether a char is ready to be read.