Thread: Detecting key press (Windows)

  1. #1
    Pawn, Pascal and C++
    Join Date
    Sep 2005
    Posts
    90

    Detecting key press (Windows)

    How can I detect if a key is currently being pressed down?
    It doesn't have to be multi-platform.
    It only needs to work on Windows.
    I'm using Bloodshed Dev-C++ if it makes any difference.

    I've tried using getch(), but it waits for a key press, rather than checking if the key is pressed down at the moment.
    Alternatively, checking what the last key to be pressed down was would work in my situation too.

    Code:
    while(1)
    {
        if(is key "x" being pressed down? or alternatively: was "x" the last key to be pressed?)
        {
            // do something
        }
    
        // do something else / continue looping 
        // regardless of wether or not the key is pressed,
        // without waiting for any input
    }
    Would be nice if someone could throw in a code example.
    Thanks in advance.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    WM_KEYDOWN (I may have added/subtracted some of the _ symbols) is probably what you're looking for, assuming you have all the <windows.h> stuff.

    (Or on the same assumption, GetKeyboardState.)
    Last edited by tabstop; 04-13-2010 at 05:44 AM.

  3. #3
    Pawn, Pascal and C++
    Join Date
    Sep 2005
    Posts
    90
    Thanks a lot tabstop, figured it out after you mentioned GetKeyboardState.
    This code will detect if the up arrow key is pressed down.

    Code:
    while(1)
    {
        if(GetKeyState(VK_UP) & 0x80)
        {
            // up arrow being pressed
        }
            
        // continue looping regardless, without waiting for any input.
    }
    Last edited by XunTric; 04-13-2010 at 06:56 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help program crashing
    By tunerfreak in forum C++ Programming
    Replies: 14
    Last Post: 05-22-2006, 11:29 AM
  2. Function to check memory left from malloc and free?
    By Lechx in forum C Programming
    Replies: 4
    Last Post: 04-24-2006, 05:45 AM
  3. Need help: wait for key press
    By Pan in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2006, 12:26 AM
  4. key press in c plz help thanks
    By fizz_uk83 in forum C Programming
    Replies: 1
    Last Post: 12-24-2002, 07:40 PM
  5. Replies: 1
    Last Post: 10-07-2001, 12:27 AM