我正在尝试监听向上和向下箭头键。我已尝试通过手动安装来使用 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;
}
你会:
关于c - 如何在 C 中监听方向键按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086775/