Detecting key press (Windows)

This is a discussion on Detecting key press (Windows) within the Windows Programming forums, part of the Platform Specific Boards category; How can I detect if a key is currently being pressed down? It doesn't have to be multi-platform. It only ...

  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,185
    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 06: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 07: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, 12:29 PM
  2. Function to check memory left from malloc and free?
    By Lechx in forum C Programming
    Replies: 4
    Last Post: 04-24-2006, 06:45 AM
  3. Need help: wait for key press
    By Pan in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2006, 01: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, 01:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21