Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a Key is pressed on C++

Tags:

c++

key

keyboard

How could I possibly check if a Key is pressed on Windows?

like image 362
snivy9014 Avatar asked Jan 11 '17 21:01

snivy9014


People also ask

How can you tell if someone pressed a key?

To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.

How do I find keystrokes in C++?

Detect Keypress in Windows Using C++ We can get the state of the key pressed using the function GetKeyState() . This function takes a virtual-key code as an argument and returns a flag telling if that key is pressed or not.

What is Kbhit ()?

The kbhit is basically the Keyboard Hit. This function is present at conio. h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero.

How do you enter in C programming?

The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable); Example: C.


1 Answers

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/) {     // Do stuff } 

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000) {     // Shift down } 

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/); bool isToggled = keyState & 1; bool isDown = keyState & 0x8000; 

Oh and also don't forget to

#include <Windows.h> 
like image 102
Frank S. Avatar answered Oct 11 '22 17:10

Frank S.