Advertisement
dmilicev

key_codes_with_getch()_v1.c

Oct 26th, 2019
355
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None
  1. /*
  2.  
  3.     key_codes_with_getch()_v1.c
  4.  
  5. Can be used to get Ascii codes for keyboard keys.
  6.  
  7. Tested on Windows 7.
  8.  
  9. Keys can be:
  10. function key  with leading 224
  11. function key  with leading   0
  12. ordinary key  nothing leading
  13.  
  14. https://stackoverflow.com/questions/10463201/getch-and-arrow-codes
  15.  
  16. getch() function returns two keycodes for arrow keys (and some other special keys).
  17. It returns either 0 (0x00) or 224 (0xE0) first,
  18. and then returns a code identifying the key that was pressed.
  19.  
  20. For the arrow keys, it returns 224 first
  21. followed by 72 (up), 80 (down), 75 (left) and 77 (right).
  22.  
  23. If the num-pad arrow keys (with NumLock off) are pressed,
  24. getch () returns 0 first instead of 224.
  25.  
  26. Please note that getch () is not standardized in any way,
  27. and these codes might vary from compiler to compiler.
  28. These codes are returned by MinGW and Visual C++ on Windows.
  29.  
  30. For MinGW and Visual C++ :
  31. These compilers use the name _getch() instead of getch()
  32. to indicate that it is a non-standard function.
  33.  
  34.  
  35.     You can find all my C programs at Dragan Milicev's pastebin:
  36.  
  37.     https://pastebin.com/u/dmilicev
  38.  
  39. */
  40.  
  41.  
  42. #include <stdio.h>
  43. #include <conio.h>
  44.  
  45.  
  46. int main()
  47. {
  48.     int ch;
  49.  
  50.     printf("\n Press a key to get it's code \t first \t int \t char \n");
  51.  
  52.     while ( (ch = _getch()) != 27 )                                 // Escape key, ESC, Ascii 27
  53.     {
  54.         if ( ch == 0 )                                              // special key with first code 0
  55.         {
  56.             printf("\n special key with first code \t   %d ", ch );
  57.             ch = _getch();                                          // let's empty that 0
  58.             printf("\t %3d \t  %c \n", ch, ch );
  59.         }
  60.         else if (ch == 224)                                         // special key with first code 224
  61.         {
  62.             printf("\n special key with first code \t %d ", ch );
  63.             ch = _getch();                                          // let's empty that 224
  64.             printf("\t %3d \t  %c \n", ch, ch );
  65.         }
  66.         else                                                        // ordinary key
  67.         {
  68.             printf("\n ordinary key \t\t\t\t %3d \t  %c \n",  ch, ch );
  69.         }
  70.     }
  71.  
  72.     printf("\n ordinary key \t\t\t\t %3d \t %c \n",  ch, ch );      // to print ESC key for exit
  73.  
  74.  
  75.     return (0);
  76. }
Advertisement
RAW Paste Data Copied
Advertisement