How to get the last key pressed without stopping the C program?

人走茶凉 提交于 2019-12-08 05:36:12

问题


Writing an application with command line interface and I would like to know at any time if F1 or ESC or an arrow key is pressed. What is the simplest way of doing this? I would like to avoid using a readline type library.

This is a Linux specific question; the program is not multithreaded.


回答1:


An implementation of kbhit() for Linux is presented in Beginning Linux Programming page 167. You can read it on-line at the link provided.

EDIT: I mention kbhit() because it was posted as a solution before it was made clear that the question related to Linux. Unfortunately the solution has been deleted, which is unfortunate. The principle is that when kbhit() returns non-zero, a subsequent blocking character-oriented read call will not block. This is only true for character oriented input; getchar() and other standard functions that read stdio are typically line-oriented, so block until newline.




回答2:


There is no way to do this in the C standard, but C implementations on various operating systems usually have some extension to do this.

On Windows, you can use getch(). On Linux and Unix, look at this question:

Non-blocking getch(), ncurses

Also, this is the very first question in the "System Dependencies" section in the C FAQ list:

19.1




回答3:


Multiple threads?



来源:https://stackoverflow.com/questions/1513344/how-to-get-the-last-key-pressed-without-stopping-the-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!