Wednesday 16 November 2011

How do I use function keys and arrow keys in my programs? in C programming

How do I use function keys and arrow keys in my programs?

The use of function keys and arrow keys in a program can make the program much easier to use. The arrow can be allowed to move the cursor, and the function keys can enable users to do special things, or they can replace commonly typed sequences of characters.

However, as is often the case with “special” features, there is no standard way to access them from within the C language. Using scanf to try to access these special characters will do you no good, and getchar cannot be depended on for this sort of operation. You need to write a small routing to query DOS for the value of the key being pressed. This method is shown in the following code:

#include <dos.h>
int GetKey()
{
union REGS in , out;
in.h.ah = 0x8;
int86( 0x21 , &in , &out );
return out.h.al;
}

This method bypasses the C input/output library and reads the next key from the key buffer. It has the
advantage that special codes are not lost, and that keys can be acted on as soon as they are pressed, instead of being stored in a buffer until Enter is pressed. Using this function, you can get the integer function of keys when they are pressed. If you write a test program

like
#include <stdio.h>
#include <dos.h>
int GetKey()
{
union REGS in , out;
in.h.ah = 0x8;
int86( 0x21 , &in , &out );
return out.h.al;
}
int main()
{
int c;
while( ( c = GetKey() ) != 27 )
/* Loop until escape is pressed */
{
printf( “Key = %d.\n” , c );
}
return 0;
}

you might get output like this for a typed string:
Key = 66.
Key = 111.
Key = 98.
Key = 32.
Key = 68.
Key = 111.
Key = 98.
Key = 98.
Key = 115.
When you press function keys or arrows, something different will happen; you will see a zero followed by a character value. This is the way special keys are represented: as a zero value followed by another, special value.

You therefore can take two actions. First, you can watch for zeros and, whenever one is pressed, treat the next character in a special fashion. Second, in the key press function, you can check for zeros and, when one is pressed, get the next value, modify it in some way, and return it. This second option is probably the better of the two options. Here’s an efficient way of getting this task done:
/*
New improved key-getting function.
*/
int GetKey()
{
union REGS in , out;
in.h.ah = 0x8;
int86( 0x21 , &in , &out );
if ( out.h.al == 0 )
return GetKey()+128;
else
return out.h.al;
}

This is the most efficient and clean of the two solutions. It will save a lot of work on the programmer’s part by saving him from having to check for special cases. Special keys have values over 128.

Cross Reference:

None.

No comments:

Post a Comment