在C语言中检测键盘事件

12

我该如何在C语言中检测键盘事件,而不使用第三方库?我应该使用信号处理吗?

5个回答

12

目前没有标准的方法,但以下内容可以帮助您入门。

Windows:

getch();

Unix:

使用W. Richard Stevens的Unix编程书中的代码将终端设置为原始模式,然后使用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;
}

4

关于老旧的 kbhit 怎么样?如果我理解问题正确,这将起作用。这里 是Linux上的kbhit实现。


3

很遗憾,标准C语言并没有提供任何检测键盘事件的功能。您需要依赖于特定于平台的扩展来实现。信号处理也无法帮助您。


3

你真的应该使用第三方库。在 ANSI C 中,绝对没有跨平台的方法来做到这一点。信号处理也不是解决问题的方法。


0
我回答有点晚,但是:
基本思路是将终端设置为非规范模式,这样你就可以逐个读取每个按键。
#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);
}

这应该足够了。

我回答晚了一点点 - 是的,大概晚了15年。希望这不是什么紧急的事情。 :-) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接