Results 1 to 3 of 3
Hi. i need to do a console aplication in c that uses special function keys. But it seems that keys like (ctrl, alt, etc) are not being passed to the ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 02-26-2006 #1Just Joined!
- Join Date
- Nov 2005
- Posts
- 44
Special key detection in C
Hi. i need to do a console aplication in c that uses special function keys. But it seems that keys like (ctrl, alt, etc) are not being passed to the app. and the special function keys just write garbage onto the screen. Any guidelines?
thanks in advance
- 02-28-2006 #2Linux Newbie
- Join Date
- Oct 2004
- Posts
- 158
ctrl-M prints as ^M, ascii 13.
What you console does with these control sequences (ASCII 1 -> 26)
is detemined by setting made with stty. Usually these settings are in /etc/profile or the user's login scripts.
ctrl, alt will not be sent to the app.
This is how to read keystrokes:
Code:#include <termios.h> #include <unistd.h> #include <assert.h> #include <string.h> /*------------------------------------------------*/ int mygetch(void) { int c=0; struct termios org_opts, new_opts; int res=0; /*----- store old settings -----------*/ res=tcgetattr(STDIN_FILENO, &org_opts); assert(res==0); /*---- set new terminal parms --------*/ memcpy(&new_opts, &org_opts, sizeof(new_opts)); new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL); tcsetattr(STDIN_FILENO, TCSANOW, &new_opts); c=getchar(); /*------ restore old settings --------- */ res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts); assert(res==0); return(c); } int main(int argc, char *argv[]) { int ch=0; while(ch!=25) /* stop on ctrl-y */ { ch=mygetch(); printf("keypress = ASCII %d %c\n", ch,ch); } return 0; }
- 03-01-2006 #3Just Joined!
- Join Date
- Nov 2005
- Posts
- 44
thanks for the trick. it is very interesting and quite useful.


Reply With Quote
