简体   繁体   English

在C中使用系统调用读取键盘事件

[英]Using system calls in C to read keyboard events

Just trying to seek to understand. 只是想寻求了解。 I'm writing a small program that will read in a keystroke event from the keyboard, and trigger certain events (using a switch statement). 我正在编写一个小程序,该程序将从键盘读取按键事件,并触发某些事件(使用switch语句)。 I'm making some assumptions, and attempting to treat the keyboard like a txt file to read from. 我正在做一些假设,并尝试将键盘像要读取的txt文件一样对待。

I'm kind of at a loss as to the simplest way to do this. 最简单的方法让我有些困惑。

What i WANT to do it open the file(keyboard event4), and use something like fgets to read it in character by character in an infinite while loop, then use a switch statement to break out of the loop and exit. 我想做的是打开文件(键盘event4),并使用fgets之类的东西在无限的while循环中逐字符读取它,然后使用switch语句退出循环并退出。

Where i'm getting stuck is the fact that these are system calls, and i'm basically unsure how to handle them. 我陷入困境的是这些是系统调用,而我基本上不确定如何处理它们。

The code below definitely won't compile, just putting it there as a rough demonstration of what i am trying to do. 下面的代码绝对不会编译,只是将其放在此处以粗略地展示我正在尝试做的事情。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{
    // errors on opening
    int fd = open("/dev/input/event4", O_RDONLY);
    if(fd < 0)
    {
        printf("error while opening/n");
        return 1;
    }

    int keystroke = 0;

    while (1)
    {
       keystroke = fgetsc(fd);

       switch(keystroke)
       {
           case '1' :
              break;
           case '2' :
              break;
           case '3' : 
              break;
           default:
              printf("waiting for 1, 2, 3/n");
          }

    close(fd);
    return 0;
}

1) Read "raw keyboard input" is generally OS-dependent. 1)读取“原始键盘输入”通常取决于操作系统。 The APIs and techniques can vary greatly depending if you're on Windows vs Linux, for example. 例如,如果您使用的是Windows vs Linux,则API和技术的差异可能很大。

2) It sounds like you're on a *nix variant (Linux or MacOS, for example). 2)听起来您使用的是* nix变体(例如Linux或MacOS)。 If you want to do all the "grunge" yourself, here's a great "howto": 如果您想自己做所有的“垃圾”工作,这里有个很棒的“方法”:

3) You'll need to put the keyboard device into "raw", "unbuffered" mode in order to read keystrokes. 3)您需要将键盘设备置于“原始”,“无缓冲”模式才能读取击键。 Among other things... 除其他事项外...

4) I would encourage you, however, to leverage a higher-level library, like ncurses or SDL . 4)但是,我鼓励您利用更高级别的库,例如ncursesSDL

'Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM