当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Keyboard input: how to separate keycodes received from user

问题描述:

I am writing an application involving user input from the keyboard. For doing it I use this way of reading the input:

#include <stdio.h>

#include <termios.h>

#include <unistd.h>

int mygetch( ) {

struct termios oldt,

newt;

int ch;

tcgetattr( STDIN_FILENO, &oldt );

newt = oldt;

newt.c_lflag &= ~( ICANON | ECHO );

tcsetattr( STDIN_FILENO, TCSANOW, &newt );

ch = getchar();

tcsetattr( STDIN_FILENO, TCSANOW, &oldt );

return ch;

}

int main(void)

{

int c;

do{

c = mygetch();

printf("%d\n",c);

}while(c!='q');

return 0;

}

Everyting works fine for letters digits,tabs but when hiting DEL, LEFT, CTRL+LEFT, F8 (and others) I receive not one but 3,4,5 or even 6 keycodes.

The question is: Is is possible to make a separation of these keycodes (to actually know that I only hit one key or key combination).

What I would like is to have a function to return a single integer value for any type of input (letter, digit, F1-F12, DEl, PGUP, PGDOWN, CTRL+A, CTRL+ALT+A, ALT+LEFT, etc). Is this possible?

I'm interested in an idea to to this, the language doesn't matter much, though I'd prefer perl or c.

Thanks,

Iulian

网友答案:

You'll want to look into the curses or ncurses libraries (or possibly slang).

Terminals, terminal windows, and the console are all modeled after actual terminals (a screen and a keyboard connected to the computer via a serial cable), and terminals are modeled after a teletype device (tty -- which is a keyboard and a simple printer).

Different terminals (real terminals, psudoterminals, and console) can have different representations for special characters, such as function and arrow keys. They do this because there are potentially more than 256 things that someone might send from between a terminal and a computer.

One of the many things curses does is takes the input that different terminal gives you and using the terminal type produces an integer which represents that key. It also provides macro constants for these values so KEY_DOWN can be compared to the result from curses' getch to determine if the down arrow was pressed.

Check out or , or you can google for curses and get lots of information.

网友答案:

Sounds like you're getting ANSI escape codes. You can break them up pretty easily using the information at this link. Your particular machine might have some special cases, but you should be able to identify and sort them out without too much trouble.

分享给朋友:
您可能感兴趣的文章:
随机阅读: