Programming and Input
Giorgos Keramidas
keramida at ceid.upatras.gr
Tue Feb 21 03:58:12 PST 2006
On 2006-02-21 13:28, Cole <cole at opteqint.net> wrote:
> Hi.
>
> Im trying to write a program that can read the Function keys, namely
> like F1, and F2, and so on. Im trying to do this using C.
The C standard doesn't really include anything about "F1", "F2", etc.
You can use system-specific libraries to handle keyboard input like
these two keys though, i.e. the ncurses library in FreeBSD.
> I just wanted to know exactly how to get it right. I know that you
> need to actually search for 2 values. Say for instance I want to
> read, F1, I know we need to first check the value to see if its
> equal to 27, and then the second value to see if its equal to 65.
> Also do I need to set stdin to be unbuffered for this?
>
> Also which function should i be using for this? Can i do something
> like this or am i totally confused?
>
> int i = 0;
> i = getc(stdin);
> if(i == 27){
> printf("we found first part\n");
This sounds very wrong. You should use a library like ncurses that
abstracts all this "hackery" with 27 and all that away, i.e.:
1 #include <curses.h>
2 #include <err.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #ifndef MAXBUF
7 #define MAXBUF 100
8 #endif
9
10 int
11 main(void)
12 {
13 char buf[MAXBUF + 1];
14 int quit;
15
16 if (initscr() == NULL)
17 err(1, "initscr");
18 if (cbreak() == ERR || noecho() == ERR || nonl() == ERR ||
19 intrflush(stdscr, FALSE) == ERR || keypad(stdscr, TRUE) == ERR) {
20 (void) endwin();
21 err(1, "curses initialization");
22 }
23
24 mvaddstr(0, 0, "Press any key or 'q' to quit");
25 refresh();
26
27 quit = 0;
28 (void) move(2, 0);
29 do {
30 int key;
31
32 key = getch();
33 switch (key) {
34 case 'q':
35 case 'Q':
36 quit = 1;
37 break;
38 default:
39 memset(buf, 0, sizeof(buf));
40 if (key < 256)
41 snprintf(buf, MAXBUF, " key %d '%c'",
42 key, (char)(key % 256));
43 else
44 snprintf(buf, MAXBUF, " key %d '?'",
45 key);
46 addstr(buf);
47 break;
48 }
49 } while (quit == 0);
50
51 if (endwin() == ERR)
52 exit(EXIT_FAILURE);
53 return 0;
54 }
Running this small curses.h example, you will see that pressing F1
doesn't generate ``27''.
> Now, from here how do I procede? If this is correct at all? Cause if I
> try to use getc to read again, I do not get 65, or any other value.
Find a good document about ncurses :)
> Please cc a copy to me since im not currently subscribed to this list.
Ok :)
Have fun,
- Giorgos
More information about the freebsd-questions
mailing list