歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux終端特殊鍵ESC序列讀取方法

Linux終端特殊鍵ESC序列讀取方法

日期:2017/2/28 16:07:00   编辑:Linux教程

采用getchar獲取終端輸入,發現特殊鍵會有多個字符,以ESC開頭,但字符數不固定。

如:向上鍵是27,91,65三個字符,F5:27,91,49,53,126是5個字符。

本來打算用取系統時間的方式來判斷這些字符是不是一起的,但不同CPU、調度情況下,可能很不穩定,所以還是得用別的辦法。

用普通的read試試看,先把終端設置成不等待讀入時間,如下:

  1. term.c_lflag &= ~ICANON;
  2. term.c_lflag &= (~ECHO);
  3. term.c_cc[VTIME] = 0;
  4. tcsetattr(STDIN_FILENO, TCSANOW, &term);
  5. for(;;)
  6. {
  7. nRead=read(STDIN_FILENO, szCmdStr, 16);
  8. if (nRead != 0)
  9. {
  10. for (tmp = 0; tmp < nRead; tmp ++)
  11. {
  12. printf("Key %d index%d\r\n", szCmdStr[tmp], tmp);
  13. if (szCmdStr[tmp] == 'q')
  14. break;
  15. }
  16. if (szCmdStr[tmp] == 'q')
  17. break;
  18. }
  19. }

輸出結果如下:

Key 10 index 0 《回車

Key 27 index 0 《向上鍵,3個字符

Key 91 index 1

Key 65 index 2

Key 27 index 0 《F12,5個字符

Key 91 index 1

Key 50 index 2

Key 52 index 3

Key 126 index 4

Key 27 index 0 《F5,5個字符

Key 91 index 1

Key 49 index 2

Key 53 index 3

Key 126 index 4

Key 113 index 0 《q

Yeah,搞定了!

Copyright © Linux教程網 All Rights Reserved