Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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

  2. #2
    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;
    }

  3. #3
    thanks for the trick. it is very interesting and quite useful.

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •