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

有帮助吗?

解决方案

没有一种标准方式,但这些方法可以让你开始。

视窗:

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;
}

其他提示

好老的 kbhit 怎么样?如果我正确理解了这个问题,这将有效。 这里是Linux上的kbhit实现。

遗憾的是,标准C没有任何检测键盘事件的工具。您必须依赖特定于平台的扩展。信号处理不会帮助你。

你真的应该使用第三方库。在ANSI C中绝对没有与平台无关的方法。信号处理不是这样的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top