访问 C 中的击键

问题描述 投票:0回答:3

我正在尝试访问 C 语言中的击键。我可以访问字母数字键。如何访问 ControlShiftAlt 键?
另外,我在某处读到,有时在控制台中输入文本时,操作系统会屏蔽退格键。我想知道用户在哪里按了退格键。这与知道什么时候'不同 ”被按下。 GNU C.Ubuntu 11。

c linux ubuntu keyboard
3个回答
2
投票

Dietrich Epp 在评论中回答:使用 ncurses 库。

另请参阅这个问题

您可能会制作一个X11客户端图形应用程序;在这种情况下,请使用图形工具包库,例如 GTKQt

如果您想制作控制台应用程序,请使用 ncurses 或可能 readline

从字面上看,你的问题没有任何意义:严格的 C 标准不知道什么是按键或击键(标准中提到的唯一 I/O 操作与

<stdio.h>
FILE
相关) 。这就是为什么大多数人使用额外的库和标准(除了 ISO C 要求的库和标准之外),例如。 Posix...


1
投票

简单的答案是“你不能”,至少不容易或者不下载第三方库。

大多数 C 程序不必了解有关键盘或屏幕的任何信息。标准 C 只关心文件的读取和写入(键盘和屏幕是特殊情况的文件)。

假设您有充分的理由想要直接访问键盘,您应该查看 ncurses 库 (http://www.gnu.org/software/ncurses/ncurses.html)。 Ncurses 知道有多少不同的(虚拟)终端和键盘在工作,并且它为它们提供了统一的界面。它允许您绘制屏幕并仅使用文本块创建替代图形界面。

由于您使用 Ubuntu,请尝试运行“aptitude”命令来查看 ncurses 功能的一个很好的示例。


0
投票

这是一个没有任何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 = 整数,以便获得键盘事件,因此您更改它并重新编译,直到您的键盘得到该值。

© www.soinside.com 2019 - 2024. All rights reserved.