Thread: Detecting Keys

  1. #1
    Registered User
    Join Date
    Jan 2010

    Detecting Keys

    I've read quite a few posts on detecting function keys using special libraries. Is it possible to read the hex value of the key intead of using a library?

    I basically want to end up with an if statement that accepts user input until <TAB>, or hex value 9, is pressed - at which point the program ends. I can't seem to capture the hex value correctly.


  2. #2
    Registered User
    Join Date
    Sep 2006
    If your compiler has conio.h as a header, then you're in luck, as this program shows:

    kbhit   Checks for currently-available keystrokes.
       int kbhit(void);
     Prototype in:
    kbhit checks to see if a keystroke is currently available.
    Any available keystrokes can be retrieved with getch or getche.
     Return Value:
    If a keystroke is available, kbhit returns a nonzero integer; if not, it
    returns 0.
    kbhit works in DOS and Windows
     See Also:
      getch    getche
    #include <conio.h>
    #include <stdio.h>
     int main(void)
        int key1;
        cprintf("Press any key to continue:");
        while (!kbhit()) /* do nothing */ ;
        //getchar() (below) is standard C. getch() is part of the 
        //non-standard (but useful), conio.h
        key1 = getch();      //get a letter, w/o an enter key being needed
        //print the int that was pressed, as a letter
        printf("\r\nA key was pressed: %c", key1);
        //print the same int as it's ascii int value
        printf("\r\nA key was pressed: %d", key1);
        printf("\n\t\t\t     Press Enter When Ready ");
        key1 = getchar();   //pause the screen from closing
        return 0;
    If you don't have conio.h, then check out the cboard tutorial on it. There's a game in the thread at first, but keep going down the replies and you'll come to the virtual keys function that MS has set up for Windows.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simulate Keys with a Keyboard Hook
    By guitarist809 in forum Windows Programming
    Replies: 3
    Last Post: 11-14-2008, 08:14 PM
  2. blocking or passing keys with global hook
    By pmouse in forum Windows Programming
    Replies: 4
    Last Post: 08-29-2007, 02:54 PM
  3. Pausing for input, with kbhit() still detecting keys
    By Da-Spit in forum C++ Programming
    Replies: 5
    Last Post: 05-23-2002, 05:04 AM
  4. detecting two keys at once using getch,switch,case
    By Unregistered in forum A Brief History of
    Replies: 9
    Last Post: 05-14-2002, 11:54 PM
  5. detecting two keys at once using getch,switch,case
    By Unregistered in forum Game Programming
    Replies: 1
    Last Post: 05-11-2002, 12:03 PM