我正在尝试访问 C 语言中的击键。我可以访问字母数字键。如何访问 Control、Shift 和 Alt 键?
另外,我在某处读到,有时在控制台中输入文本时,操作系统会屏蔽退格键。我想知道用户在哪里按了退格键。这与知道什么时候'不同
”被按下。
GNU C.Ubuntu 11。
简单的答案是“你不能”,至少不容易或者不下载第三方库。
大多数 C 程序不必了解有关键盘或屏幕的任何信息。标准 C 只关心文件的读取和写入(键盘和屏幕是特殊情况的文件)。
假设您有充分的理由想要直接访问键盘,您应该查看 ncurses 库 (http://www.gnu.org/software/ncurses/ncurses.html)。 Ncurses 知道有多少不同的(虚拟)终端和键盘在工作,并且它为它们提供了统一的界面。它允许您绘制屏幕并仅使用文本块创建替代图形界面。
由于您使用 Ubuntu,请尝试运行“aptitude”命令来查看 ncurses 功能的一个很好的示例。
这是一个没有任何lib的c的正确解决方案
#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;
}
因此您偶尔需要更改 eventx 处的值,其中 x = 整数,以便获得键盘事件,因此您更改它并重新编译,直到您的键盘得到该值。