Reputation:
I am trying to access keystrokes in C. I can access alphanumeric keys. How can I access Control, Shift and Alt key?
Plus I read somewhere that sometimes while entering text in console, OS masks backspace key. I would like to know where user pressed backspace key. It's not same as knowing when '\n' was pressed.
GNU C. Ubuntu 11.
Upvotes: 1
Views: 4031
Reputation: 173
here is a correct solution with c without any lib
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
int main() {
int fd;
struct input_event ev;
// Open the input device file
fd = open("/dev/input/event0", O_RDONLY);
if (fd == -1) {
perror("Error opening input device");
return 1;
}
while (1) {
// Read the next input event
if (read(fd, &ev, sizeof(struct input_event)) == sizeof(struct input_event)) {
// Check if the event is a key press
if (ev.type == EV_KEY && ev.value == 1) {
printf("Key pressed: %d\n", ev.code);
if (ev.code == KEY_Q) // Check if 'q' key is pressed
break;
}
}
}
// Close the input device file
close(fd);
return 0;
}
so you occasionally need to change the value at eventx where x = integer, to get you keybaord event you change it and recompiled until that for your keyboard.
Upvotes: 0
Reputation: 6752
The simple answer is "you can't", at least not easily or without downloading third party libraries.
Most C programs shouldn't have to know anything about the keyboard or the screen. Standard C is only concerned with reading from and writing to files (the keyboard and screen being special-case files).
Assuming you have a good reason for wanting to access the keyboard directly, you should be looking at the ncurses library (http://www.gnu.org/software/ncurses/ncurses.html). Ncurses knows how many different (virtual) terminals and keyboards work, and it presents a uniform interface to them. It lets you paint the screen and create a substitute graphical interface using only blocks of text.
Since you use Ubuntu, try running the "aptitude" command to see a good example of what ncurses can do.
Upvotes: 1
Reputation: 1
Dietrich Epp answered in a comment: use ncurses library.
See also this question
And you might make an X11 client graphical application; in that case use a graphical toolkit library like GTK or Qt
If you want to make a console application, use ncurses or perhaps readline
And your question, when taken literally, has no sense: the strict C standard don't know what a key or a keystroke is (the only I/O operations mentioned in the standard are related to <stdio.h>
thru FILE
). This is why most people uses additional libraries and standards (in addition of those required by ISO C), eg. Posix...
Upvotes: 2