Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a function to check for key press in unix using ncurses

I have been looking for an equivalent to kbhit() and I have read several forums on this subject, and the majority seem to suggest using ncurses.

How should I go about checking if a key is pressed in C++ using ncurses?

The function getch() provided by ncurses reads a character from the window. I would like to write a function that only checks if there is a key press and then I want to do getch().

like image 917
Mimsy Jack Avatar asked Oct 26 '10 16:10

Mimsy Jack


People also ask

How do you check if a key is pressed in C Linux?

You can use getchar() or getc(stdin) , these are standard functions in C. They echo the character to the terminal that was pressed. getchar() function will wait for input from keyboard, if we don't press any key it will continue to be in the same state and program execution stops there itself untill we press a key.

How do I submit Ncurses?

To use ncurses library functions, you have to include ncurses. h in your programs. To link the program with ncurses the flag -lncurses should be added.


1 Answers

You can use the nodelay() function to turn getch() into a non-blocking call, which returns ERR if no key-press is available. If a key-press is available, it is pulled from the input queue, but you can push it back onto the queue if you like with ungetch().

#include <ncurses.h>
#include <unistd.h>  /* only for sleep() */

int kbhit(void)
{
    int ch = getch();

    if (ch != ERR) {
        ungetch(ch);
        return 1;
    } else {
        return 0;
    }
}

int main(void)
{
    initscr();

    cbreak();
    noecho();
    nodelay(stdscr, TRUE);

    scrollok(stdscr, TRUE);
    while (1) {
        if (kbhit()) {
            printw("Key pressed! It was: %d\n", getch());
            refresh();
        } else {
            printw("No key pressed yet...\n");
            refresh();
            sleep(1);
        }
    }
}
like image 67
Matthew Slattery Avatar answered Oct 26 '22 14:10

Matthew Slattery