【问题标题】:Keyboard handler in CC 中的键盘处理程序
【发布时间】:2014-10-29 19:24:18
【问题描述】:

在 C 中,我如何编写一个程序来告诉我按下了哪些键?例如,它应该输出

You pressed F1 key
You pressed ESC key
You released F1 key

如果同时按下 F1 和 q 键,则转到 Linux 控制台并结束程序。

我试过了

#include <curses.h>  // required

int r,c,  // current row and column (upper-left is (0,0))
    nrows,  // number of rows in window
    ncols;  // number of columns in window

void draw(char dc)

{  move(r,c);  // curses call to move cursor to row r, column c
   delch();  insch(dc);  // curses calls to replace character under cursor by dc
   refresh();  // curses call to update screen
   r++;  // go to next row
   // check for need to shift right or wrap around
   if (r == nrows)  {
      r = 0;
      c++;
      if (c == ncols) c = 0;
   }
}

main()

{  int i;  char d;
   WINDOW *wnd;

   wnd = initscr();  // curses call to initialize window
   cbreak();  // curses call to set no waiting for Enter key
   noecho();  // curses call to set no echoing
   getmaxyx(wnd,nrows,ncols);  // curses call to find size of window
   clear();  // curses call to clear screen, send cursor to position (0,0)
   refresh();  // curses call to implement all changes since last refresh

   r = 0; c = 0;
   while (1)  {
      d = getch();  // curses call to input from keyboard
      if (d == 'q') break;  // quit?
      draw(d);  // draw the character
   }

   endwin();  // curses call to restore the original window and leave

}

但它有问题,例如识别 shift 键和 valgrind 说

==11693==    still reachable: 59,676 bytes in 97 blocks

【问题讨论】:

  • 我尝试了 ncurses,但 valgrind 说我有一些内存泄漏,我的代码无法识别所有键。
  • 这太宽泛了,除非您有一些您尝试过的代码,否则您应该删除它或将其移至程序员 Stack Exchange。如果你有代码。请把它编辑成问题,这样我们就可以看到你已经走了多远。

标签: c linux keyboard


【解决方案1】:

首先,请注意这不是 C 题;答案是特定于 Linux 的。 C 语言不提供键盘 API。

要检测按键和释放,您必须比

更深入
  • Linux 终端驱动程序的默认行为(所谓的“熟”模式),它允许您一次读取一行字符,使用诸如getcscanf 之类的函数,以及
  • 驱动程序所谓的“原始”模式,它会向您的应用程序传递每个按下的键,现代编辑器和外壳程序使用该模式,并由 curses API 提供。

您可以通过查看输入事件来做到这一点。请参阅标题 input.hcorresponding articlean example of its use。请注意,通过此 API,您可以获得较低级别的信息:按键扫描代码,而不是 ASCII 或 Unicode 代码,以及按键 (EV_KEY)、按键 (EV_REL) 事件而不是按键。

【讨论】:

    【解决方案2】:

    您可以使用简单的scanf/printf 轻松检测“经典”输入(字母、数字和符号)(您应该在UnicodeUTF-8 中获得输入代码)。

    对于“特殊”键:查看there

    似乎没有标准的方法可以做到这一点,但提供了一些第三方库的链接,希望能有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 2019-05-01
      • 2016-05-15
      • 2014-05-09
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      相关资源
      最近更新 更多