Reputation: 16029
How can I detect keyboard event in C language without using third party libraries? Should I use signal handling?
Upvotes: 12
Views: 24657
Reputation: 1
I'm a little late to answer, but:
The basic idea is to set the terminal to non-canonical mode so that you can read each keypress individually.
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
void setNonCanonicalMode() {
struct termios term;
tcgetattr(STDIN_FILENO, &term);
term.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &term);
}
void resetCanonicalMode() {
struct termios term;
tcgetattr(STDIN_FILENO, &term);
term.c_lflag |= ICANON | ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &term);
}
This should suffice.
Upvotes: 0
Reputation: 3138
What about good old kbhit ? If I understand the question correctly this will work. Here is the kbhit implementation on Linux.
Upvotes: 4
Reputation: 304434
There's not a standard way, but these should get you started.
Windows:
getch();
Unix:
Use this code from W. Richard Stevens' Unix Programming book to set your terminal in raw mode, and then use read().
static struct termios save_termios;
static int term_saved;
int tty_raw(int fd) { /* RAW! mode */
struct termios buf;
if (tcgetattr(fd, &save_termios) < 0) /* get the original state */
return -1;
buf = save_termios;
buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* echo off, canonical mode off, extended input
processing off, signal chars off */
buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
/* no SIGINT on BREAK, CR-toNL off, input parity
check off, don't strip the 8th bit on input,
ouput flow control off */
buf.c_cflag &= ~(CSIZE | PARENB);
/* clear size bits, parity checking off */
buf.c_cflag |= CS8;
/* set 8 bits/char */
buf.c_oflag &= ~(OPOST);
/* output processing off */
buf.c_cc[VMIN] = 1; /* 1 byte at a time */
buf.c_cc[VTIME] = 0; /* no timer on input */
if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
return -1;
term_saved = 1;
return 0;
}
int tty_reset(int fd) { /* set it to normal! */
if (term_saved)
if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
return -1;
return 0;
}
Upvotes: 12
Reputation: 400174
You really should use third party libraries. There's definitely no platform-independent way to do it in ANSI C. Signal handling is not the way.
Upvotes: 3
Reputation: 64404
Standard C does not have any facilities for detecting keyboard events, unfortunately. You have to rely on platform-specific extensions. Signal handling wont help you.
Upvotes: 3