How do you read the arrow keys?

Mike Stefanik/78125 mike at bria.AIX
Sun Dec 30 22:21:23 AEST 1990


In article <1990Dec28.195518.26577 at ivy.uucp>, iverson at ivy.uucp (Tim Iverson) writes:
> There're going to be alot of responses about getting curses to decode your
> keys for you.  And, yes, it will do it, but it has a major problem: no
> timeouts; e.g. left arrow on a vt100 (or pc ansi console) is <esc>[D, so if
> your user hits <esc>, curses waits for the next char to come along before
> it knows to return the <esc> as a key.

Actually, this isn't true, at least with the curses packages that I've been
using.  The idea is to do something like this:

	ttystate(mode)
	int mode;
	{
	static struct termio	old, new;

		if ( mode == 1 ) {
			ioctl(0,TCGETA,&old);
			ioctl(0,TCGETA,&new);

			new.c_lflag &= ~ECHO;
			new.c_lflag &= ~ICANON;
			new.c_lflag &= ~ISIG;
			new.c_cc[VMIN] = MAXCHARS;
			new.c_cc[VTIME] = TIMEOUT; 

			ioctl(0,TCSETA,&new);
			}
		else
			ioctl(0,TCSETA,&old);
	}

Where MAXCHARS is approx. the longest number of characters that can be
returned by a function/editing key, and TIMEOUT is usually 1 (1/10th of
a second).

When stdin is read, the read() will return when either:
	a) MAXCHARS have been read
	b) TIMEOUT has expired

Therefore, if the user just presses ESC, it is easy to determine if
it was an escape key or part of a sequence such as ESC[D ... just look at
the number of characters returned by read().  It gets trickier if the
pesky user is holding down the arrow key, which can generate multiple
escape sequences within the timeframe of the read; that's why it's good
to set the MAXCHARS value to something approximating the length of the
escape sequence ... if the user is holding down the key, the first 
sequence with satisfy MAXCHARS, and cause the read() to return, with the
remaining sequences still in the input buffer.

Hope this helps.

-----------------------------------------------------------------------------
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
"If it was hard to code, it should be harder to use!"



More information about the Comp.unix.programmer mailing list