LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   kbhit() (https://www.linuxquestions.org/questions/programming-9/kbhit-34027/)

iceman47 10-28-2002 02:51 PM

kbhit()
 
I'll rewrite my question here after posting it in the wrong place :( .
Is there an alternative for the function kbhit() as included in Borland's conio.h?
Thanks again.

Hko 10-28-2002 04:40 PM

Here's a complete example program that should get you there. Link it with the ncurses libs.

Code:

#include <stdio.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#include <unistd.h>

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\n");
        sleep(1);
        if(kbhit()) {
            ch = readch();
            printf("you hit %c\n",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;
}

From the downloaded sources (GPL'd) of the book "Beginning Linux Programming" - Wrox.

iceman47 10-28-2002 05:09 PM

That helped me alot. Thanks once more for your time

HarryBoy 05-22-2008 10:55 AM

Great
 
This is a great post and has helped me loads.

How can I modify this to detect the arrow keys?

Thanks

Harry

Wim Sturkenboom 05-22-2008 11:21 PM

Use printf("you hit %0x02x\n",ch); instead of the original printf.
It will tell you (in hex) which data is received. Next you can analyse and modify the code to do what it needs to do.

I seem to remember that (at least in DOS) you will get two bytes back when you hit the arrow keys, home etc.

smeezekitty 09-20-2009 12:34 PM

why not just generate interrupt 16h


All times are GMT -5. The time now is 07:31 AM.