LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Trapping keystrokes in C (https://www.linuxquestions.org/questions/programming-9/trapping-keystrokes-in-c-48620/)

k4zau 03-06-2003 06:19 PM

Trapping keystrokes in C
 
I am trying to build a program with C, which will run as a text-mode console application under Linux. I need some functions to respond on a keystroke, e.g. anytime the user presses 'h' a help screen pops up. I don't want the user to have to press [enter] after the keystroke and I also want to be able to capture the [enter] key by itself.

I've read that this can be done under curses, but I want this to remain a strictly text-mode app. I also read that there is a function getch() in <conio.h> that seems to be what I'm looking for; I put these into a sample program and the compiler (gcc) didn't recognize either one. Are those in C++ only? I'm pretty knowledgeable about Basic, but I know much less about C.

Thanks

Dark_Helmet 03-06-2003 06:40 PM

getch(0 does exist, but I don't remember the header it is in off-hand. conio.h sounds very familiar though.

Interesting, I just tried "man getch" and the system said it was in curses.h. It would probably do what you need.

aditya 03-07-2003 05:29 AM

Hi,
I don't think getch() will solve your problem if I've understood it, becasue you said the program should respond anytime "h" is pressed, but getch() works at a point, and is exactly an an unbuffered and not-echo getchar() only.
What you need is signal handling. So that the user can do whatever he is doing, and at any time he presses "Cntrl-h" or something you've defined, the execution passes to the handler and the popup help menu is visible.

adi

k4zau 03-09-2003 02:13 PM

Thanks for your suggestions.

I did another (better) search on the Net, and found some free sourcecode that emulates getch() under Unix/Linux. I'll probably try to use that.

Actually, the user will have a prompt in my program where commands will be entered; I just didn't want them to have to press Enter afterwards. Being as the prompt is always on the screen and there aren't going to be any other processes running, I'm pretty sure that getch() will work.


All times are GMT -5. The time now is 11:05 AM.