Input event loop in a console application
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 开发者_JS百科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
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...
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.
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.
To change stdin to not buffer until enter is hit, you can mess around with the terminal i/o settings like so..
struct termios oldopts;
struct termios newopts;
tcgetattr(fileno(stdin), &oldopts);
newopts = oldopts;
newopts.c_lflag &= (~ICANON & ~ECHO);
tcsetattr(fileno(stdin), TCSANOW, &newopts);
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.
精彩评论