【问题标题】:Detect Keyboard Event in C检测 C 中的键盘事件
【发布时间】:2010-09-18 06:16:20
【问题描述】:

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

【问题讨论】:

    标签: c keyboard


    【解决方案1】:

    没有标准的方法,但这些应该可以帮助您入门。

    窗户:

    getch();
    

    Unix:

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

    【讨论】:

      【解决方案2】:

      那好老的kbhit 呢?如果我正确理解了这个问题,这将起作用。 Here 是 Linux 上的 kbhit 实现。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          您确实应该使用第三方库。在 ANSI C 中绝对没有独立于平台的方法。信号处理不是这种方法。

          【讨论】:

            猜你喜欢
            • 2017-04-06
            • 1970-01-01
            • 2014-06-22
            • 2015-06-26
            • 1970-01-01
            • 2016-12-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多