C语言中的键盘处理程序

C语言中的键盘处理程序,c,linux,keyboard,C,Linux,Keyboard,在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

在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

}
您可以通过一个简单的
scanf
/
printf
(您应该以编码方式获取输入的代码)轻松检测“经典”输入(字母、数字和符号)

对于“特殊”键:请看一看


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

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

要检测按键和释放,您必须深入到

  • Linux终端驱动程序的默认行为(所谓的“煮熟”模式),它允许您使用
    getc
    scanf
    等函数一次读取一行字符,以及
  • 驱动程序的所谓“原始”模式,它将现代编辑器和shell使用的、由API提供的每个按下的键传递给应用程序

您可以通过查看输入事件来实现这一点。请参见页眉、a和。请注意,通过此API,您可以获得较低级别的信息:按键扫描代码,而不是ASCII或Unicode代码,以及按键向下(
EV_key
),按键向上(
EV_REL
)事件,而不是按键。我尝试了ncurses,但valgrind说我有一些内存泄漏,我的代码无法识别所有按键。这太广泛了,除非您有一些您尝试过的代码,否则您应该将其删除或移动到程序员堆栈交换。如果你有代码。请把它编辑成问题,这样我们就可以看到你已经走了多远。
==11693==    still reachable: 59,676 bytes in 97 blocks