c - 如何在 C 中监听方向键按下

标签 c linux

我正在尝试监听向上和向下箭头键。我已尝试通过手动安装来使用 conio.h,但它也不起作用 — 我遇到了错误。我正在使用 Kali Linux。

我的代码:

#include <stdio.h>
#include <conio.h>
#include <curses.h>
int main() {

int ch = getch();

return 0;
}

错误:

/usr/bin/ld: /tmp/cckPLPKN.o: in function `main': test.c:(.text+0x9):
undefined reference to `getch' collect2: error: ld returned 1 exit
status

最佳答案

这应该可以解决问题 🤓:

对于 Windows:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main(){
   int ch;

   printf("Press # to Exit\n");

   while ((ch = getch()) != '#'){
      if (ch == 0 || ch == 224) {
         switch (getch()) {
            case 72:
               printf("\nUp Arrow");
               break;
            case 80:
               printf("\nDown Arrow");
               break;
            case 77:
               printf("\nRight Arrow");
               break;
            case 75:
               printf("\nLeft Arrow");
               break;
         }
      }
   }

   return 0;
}

对于 Linux:

#include <curses.h>

int main() {
  
    int ch;
    
    /* Curses Initialisations */ 
    initscr();                  /* curses initialization */
    keypad(stdscr, TRUE);       /* enable KEY_UP/KEY_DOWN/KEY_RIGHT/KEY_LEFT */
    noecho();                   /* prevent displaying if other keys */
    
    printw("Press # to Exit\n");
 
    while ((ch = getch ()) != '#') {
        switch (ch) {
            case KEY_UP:
                printw ("\nUp Arrow");
                break;
            case KEY_DOWN:
                printw ("\nDown Arrow");
                break;
            case KEY_RIGHT:
                printw ("\nLeft Arrow");
                break;
            case KEY_LEFT:
                printw ("\nRight Arrow");
                break;
        }
    }
 
    return 0;
}

你会:

enter image description here

关于c - 如何在 C 中监听方向键按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086775/

相关文章:

c - 执行全部代码后得到 "segmentation fault"

linux - 将输出存储在变量中并在命令中使用变量

linux - Nginx: curl: (60) SSL证书问题:无法获取本地颁发者证书

c - 如何在头文件中声明锯齿状数组?

objective-c - 在 MacOS 10.10 上监视文件系统事件

c++ - 将数组中的简单数据类型移动到特定位置的最快方法

python - 隐藏从自定义 CLI 应用程序生成的 json 文件格式数据?

java - 在 Ubuntu 上安装 Eclipse/Java

linux - 在没有 ping 的情况下从命令行测试主机名是否存在

C - 需要解释 printf 选项的行为