| | |
How do you check if arrow keys are pressed?
![]() |
I know they don't have standard ASCII values, but how do you check for them?
I am making a command prompt-type interface for a text-based RPG a friend and I are making, and I would like to be able to use the arrow keys to navigate in menus.
I am using getch(); in a do-while loop. The exiting condition of the loop is the user hits ENTER. This loop just keeps putting chars (gotten from getch() ) into a char array, with 0D hex or '\n' being the char that the loop stops on. Just a real simple loop. I included the following line into my developmental program to see what the values are of the keys that you press:
and when the UP arrow key is pressed, this line displays " 0 H 72", with " 0 H" being the value of the UP arrow key. This apparently doesn't look like it will fit into a char, so how would I code for it? Because I wrote a function that displayed the length of the string passed to it and it said the string length was 0 characters long. It looks like the UP arrow key has the value of 72, but this is incorrect, because capital h has this decimal value, which leads me to believe that there are possibly NULL characters in the " 0 H", because my function that returns the length of the string counts '\0' (or NULL) as the end of the string. At face value, this looks like the "string" is 4 characters long.
But if the first 'char' in it is not a space, and instead, actually a NULL character, then it would return 0 characters long just like it is doing.
So what do you recommend me doing to check to see if the user hits an arrow key? I would like it to work just like the command prompt in DOS or Windows...when the user hits left or right, it takes them left or right one character in the text they have entered on the line. And when they hit up or down, it takes them up or down one command in their command history.
Thanks,
Diode
I am making a command prompt-type interface for a text-based RPG a friend and I are making, and I would like to be able to use the arrow keys to navigate in menus.
I am using getch(); in a do-while loop. The exiting condition of the loop is the user hits ENTER. This loop just keeps putting chars (gotten from getch() ) into a char array, with 0D hex or '\n' being the char that the loop stops on. Just a real simple loop. I included the following line into my developmental program to see what the values are of the keys that you press:
C Syntax (Toggle Plain Text)
printf("%c %d ", str[num], str[num]);
and when the UP arrow key is pressed, this line displays " 0 H 72", with " 0 H" being the value of the UP arrow key. This apparently doesn't look like it will fit into a char, so how would I code for it? Because I wrote a function that displayed the length of the string passed to it and it said the string length was 0 characters long. It looks like the UP arrow key has the value of 72, but this is incorrect, because capital h has this decimal value, which leads me to believe that there are possibly NULL characters in the " 0 H", because my function that returns the length of the string counts '\0' (or NULL) as the end of the string. At face value, this looks like the "string" is 4 characters long.
But if the first 'char' in it is not a space, and instead, actually a NULL character, then it would return 0 characters long just like it is doing.
So what do you recommend me doing to check to see if the user hits an arrow key? I would like it to work just like the command prompt in DOS or Windows...when the user hits left or right, it takes them left or right one character in the text they have entered on the line. And when they hit up or down, it takes them up or down one command in their command history.
Thanks,
Diode
Oops, I quickly realized that I was inaccurate in stating that the UP arrow key contained 4 characters. I forgot about that line of code I supplied which includes spaces and values.
The UP arrow key really contains: two characters. The first character is a NULL space, or '\0', and the second character is a capital h, 'H'.
Sorry for the mix up.
Diode
The UP arrow key really contains: two characters. The first character is a NULL space, or '\0', and the second character is a capital h, 'H'.
Sorry for the mix up.
Diode
Wait, wait! How did you do it, Diode?
(I don't mean to hijack the thread, but this is more efficient than posting
another thread asking the same thing, only to have Diode answer the question)
(I don't mean to hijack the thread, but this is more efficient than posting
another thread asking the same thing, only to have Diode answer the question)
Last edited by FireSBurnsmuP; Sep 22nd, 2006 at 3:29 pm. Reason: disclaimer, I don't like ruffling the mods' feathers
I usually do it with this:
You can use this to discover what the key values are.
This only works for compilers that have
C Syntax (Toggle Plain Text)
if (kbhit()) { ch1 = getch(); if (ch1 != '\0') { // process a normal keystroke } else { ch2 = getch(); // get the arrow or function key switch(ch2) { // process the arrow or function key } } }
This only works for compilers that have
getch() and kbhit() defined, of course. The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
This compiled with no errors on Borland C++ 5 and gcc. So this should compile on yours.
I hope this was helpful to some people.
Cheers,
Diode
C Syntax (Toggle Plain Text)
/******************************* 0026.c *******************************/ /* */ /* Date: September 22, 2006 */ /* Author: diode */ /* ndweiler@mchsi.com */ /* Purpose: To practice checking for arrow keys being pressed */ /* in a header file */ /* */ /**********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #include <process.h> #include <ctype.h> #define STRING_LENGTH 100 #define ARROW_KEY_NONE 0 #define ARROW_KEY_UP 1 #define ARROW_KEY_DOWN 2 #define ARROW_KEY_LEFT 3 #define ARROW_KEY_RIGHT 4 #define ARROW_KEY_POSSIBLE 5 // BEGINNING OF PROTOTYPES void settext(void); void getline(char * str2); void showoutput(char * str2); int checkarrowkey(char key); // BEGINNING OF PROGRAM int main() { char strexit[STRING_LENGTH]; char strquit[STRING_LENGTH]; char holdtextline[STRING_LENGTH]; system("cls"); holdtextline[0] = '\0'; getline(holdtextline); showoutput(holdtextline); printf("\n"); return 0; } // END OF PROGRAM // BEGINNING OF FUNCTIONS void settext(void) { char text; text = getch(); // holds the output on screen } void getline(char * str2) { char str1[STRING_LENGTH]; int num = 0; int checkkey = 0; // used to check for special keys printf("Enter your text:"); // instructs you to enter something do // starts loop for input { if (num == STRING_LENGTH) { break; // exits when the string fills up } else { str1[num] = getch(); // puts a char into 'str' } if ((str1[num] == '\b') && (num <= 0)) // starts the backspace handler { // if you're at the beginning... // do nothing } else // but if everything's alright... { ///////////////////////////////////////////////////////////////// // This is where I check to see if the user typed an arrow ///////////////////////////////////////////////////////////////// if((str1[num] == '\0') && (num >= 0)) { num++; goto last; } else { if((num > 0) && (str1[num - 1] == '\0') && (str1[num] != '\0')) { checkkey = checkarrowkey(str1[num]); switch(checkkey) { case ARROW_KEY_UP: printf("\nYou pressed the UP arrow key!"); return; case ARROW_KEY_DOWN: printf("\nYou pressed the DOWN arrow key!"); return; case ARROW_KEY_LEFT: printf("\nYou pressed the LEFT arrow key!"); return; case ARROW_KEY_RIGHT: printf("\nYou pressed the RIGHT arrow key!"); return; default: return; } } } ///////////////////////////////////////////////////////////////// // This ends where I check to see if the user typed an arrow ///////////////////////////////////////////////////////////////// printf("%c", str1[num]); // echoes your char to the screen } str1[num] = tolower(str1[num]); // converts it to lowercase if ((str1[num] == '\b') && (num >= 1)) // removes the last-typed char { // from the screen and from the printf(" \b"); // string str1[num - 1] = '\0'; // num = num - 1; // } else { if (str1[num] != '\b') // if everything is alright... { // num++; // it increments 'num' by 1 } } last: } while(str1[num-1] != 0x0D); // loops until ENTER is hit str1[num - 1] = '\0'; // create the NULL string char strcpy(str2, str1); // copy 'str1' to 'str2' } void showoutput(char * str2) // beginning of 'showoutput' { int length = strlen(str2); // sets 'length' to the length of // the string 'str2' printf("\n\nYour text was '%s' ", str2); // outputs 'str2' to screen printf("\n'%s' is %d characters long",// outputs 'str2' and its str2, length); // length to the screen } int checkarrowkey(char key) { int whichkey = 0; char str1 = '\0'; //char str2[STRING_LENGTH]; str1 = key; switch(str1) { case 'H': whichkey = ARROW_KEY_UP; return whichkey; case 'P': whichkey = ARROW_KEY_DOWN; return whichkey; case 'K': whichkey = ARROW_KEY_LEFT; return whichkey; case 'M': whichkey = ARROW_KEY_RIGHT; return whichkey; default: return 0; } }
I hope this was helpful to some people.
Cheers,

Diode
•
•
•
•
I usually do it with this:
You can use this to discover what the key values are.C Syntax (Toggle Plain Text)
if (kbhit()) { ch1 = getch(); if (ch1 != '\0') { // process a normal keystroke } else { ch2 = getch(); // get the arrow or function key switch(ch2) { // process the arrow or function key } } }
This only works for compilers that havegetch()andkbhit()defined, of course.
What is the top decimal value that kbhit() catches when you hit a key? I didn't know about kbhit. So I coded the entire thing from scratch. It works. But the UP arrow key for example is " H", that is: NULL, capital h. It is actually 2 characters. Does kbhit() catch 2 characters? And could you provide a sample program that prints on the screen that an arrow key was hit, like I coded my sample program? I am curious about this apparent quick way that you provided.
Thanks,

Diode
![]() |
Similar Threads
Other Threads in the C Forum
- Previous Thread: Please help me in libpng1.2.33
- Next Thread: Split / explode-like function
| Thread Tools | Search this Thread |
* ansi api array arrays bash binarysearch calculate centimeter changingto char character convert copyanyfile copypdffile createcopyoffile createprocess() csyntax directory dynamic fflush file floatingpointvalidation fork forloop frequency function getlasterror getlogicaldrivestrin givemetehcodez graphics gtkgcurlcompiling gtkwinlinux hardware highest histogram homework i/o ide inches initialization intmain() iso km license linked linkedlist linux linuxsegmentationfault list logical_drives looping loopinsideloop. lowest match matrix microsoft motherboard mqqueue mysql oddnumber odf open opendocumentformat openwebfoundation pdf pointer pointers posix power program programming pyramidusingturboccodes read recursion recv recvblocked repetition reversing scanf scheduling segmentationfault send shape single socketprogramming stack standard strchr string suggestions test unix urboc user variable whythiscodecausesegmentationfault win32api windows.h windowsapi






