Capturing Keypresses

hi,


would anyone happen to know how I can capture a keystroke (like using kbhit in Borland c) in unix or linux?


than'x


Steven


Comments

  • You can use ncurses, or getch() to grab a single char,

    or just read from stdin.


    The Wrox 'beginning linux programming' book had

    this exact utility in it -- the source code is avail

    at wrox.com but I'll post it here:




    #include

    #include

    #include

    #include

    #include


    static struct termios initial_settings, new_settings;

    static int peek_character = -1;


    void init_keyboard();

    void close_keyboard();

    int kbhit();

    int readch();


    int main()

    {

    int ch = 0;


    init_keyboard();

    while(ch != 'q') {

    printf("looping
    ");

    sleep(1);

    if(kbhit()) {

    ch = readch();

    printf("you hit %c
    ",ch);

    }

    }

    close_keyboard();

    exit(0);

    }


    void init_keyboard()

    {

    tcgetattr(0,&initial_settings);

    new_settings = initial_settings;

    new_settings.c_lflag &= ~ICANON;

    new_settings.c_lflag &= ~ECHO;

    new_settings.c_lflag &= ~ISIG;

    new_settings.c_cc[VMIN] = 1;

    new_settings.c_cc[VTIME] = 0;

    tcsetattr(0, TCSANOW, &new_settings);

    }


    void close_keyboard()

    {

    tcsetattr(0, TCSANOW, &initial_settings);

    }


    int kbhit()

    {

    char ch;

    int nread;


    if(peek_character != -1)

    return 1;

    new_settings.c_cc[VMIN]=0;

    tcsetattr(0, TCSANOW, &new_settings);

    nread = read(0,&ch,1);

    new_settings.c_cc[VMIN]=1;

    tcsetattr(0, TCSANOW, &new_settings);


    if(nread == 1) {

    peek_character = ch;

    return 1;

    }

    return 0;

    }


    int readch()

    {

    char ch;


    if(peek_character != -1) {

    ch = peek_character;

    peek_character = -1;

    return ch;

    }

    read(0,&ch,1);

    return ch;

    }



    BTW, the book is pretty good, especially if you've

    never programmed Unix before. I think that AW's

    'Linux Application Development' is better, though

    the Wrox book covers more [& is less in-depth] and

    is a great up-and-running guide for the linux

    programming tools.




    _m


  • : hi,


    : would anyone happen to know how I can capture a keystroke (like using kbhit in Borland c) in unix or linux?


    : than'x


    : Steven





Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories