Get key press in windows console
If stuff like control and alt keys, these are virtual key strokes, they are supplements to characters. You will need to use ReadConsoleInput
. But you will get it all, the mouse also. So you really need to filter and return a structure from the call so you know if it is the likes of ctrl-A Alt-A. Filter repeats if you don't want them.
This may need work, don't know what you are after...
bool getconchar( KEY_EVENT_RECORD& krec )
{
DWORD cc;
INPUT_RECORD irec;
HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
if (h == NULL)
{
return false; // console not found
}
for( ; ; )
{
ReadConsoleInput( h, &irec, 1, &cc );
if( irec.EventType == KEY_EVENT
&& ((KEY_EVENT_RECORD&)irec.Event).bKeyDown
)//&& ! ((KEY_EVENT_RECORD&)irec.Event).wRepeatCount )
{
krec= (KEY_EVENT_RECORD&)irec.Event;
return true;
}
}
return false; //future ????
}
int main( )
{
KEY_EVENT_RECORD key;
for( ; ; )
{
getconchar( key );
std::cout << "key: " << key.uChar.AsciiChar
<< " code: " << key.wVirtualKeyCode << std::endl;
}
}
ReadConsoleInput function
INPUT_RECORD structure
KEY_EVENT_RECORD structure
Virtual-Key Codes
How can I detect if any key is pressed in C++?
_kbhit allows you to check whether a key has been pressed. Unlike _getch it returns immediately, and doesn't block in case there is no data in the input buffer to be read.
Both functions are Microsoft-specific extensions to the C Runtime (CRT), and aren't part of Standard C or C++.
Answers to secondary questions:
I'm concerned that my program won't even be able to detect any input because of the sleep function pausing the execution.
Console input is handled by the OS, and buffered for you while you aren't listening for input. The thread reading from console input need not be awake at the time the input arrives. It will always be able to observe input from the buffer when it wakes up to check.
If this is the case, what would be a better approach to this?
This won't happen. And yet, there are better options to implement the requirements. As it's currently implemented, the application will not be able to respond to input before the Sleep
timeout expires. While reliable, this results in an observable delay between the user hitting a key and the application responding to it.
There are ways to address this. Both the Windows API as well as the C++ programming language offer services that allow you to implement a wait operation that returns as soon as one of several conditions is met (e.g. wait until a key is pressed or a timeout has expired).
The solutions are involved and require profound familiarity with the Windows API or C++ – ideally both – to digest. I doubt you'd benefit much (to try) to learn those at this point. Continue your journey and come back to this at a later time, enjoying the comfort of knowing that this can be solved.
How do I check if a Key is pressed on C++
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>
How to get keypress event in console
I recommend having a read through here. I think
getchar()
might be what you're after.
EDIT: In fact possibly
#include <conio.h>
_getch()
would work better for you as it does not require the end of line character (enter button to be pressed). For windows refer to this and for unix systems this seems to be included in the curses library.
Hope this helps!
Console get key press w/o windows messages c++
There's conio.h but it's not technically standard. On Linux, my first Google hit suggests termios.h.
Detect a key press in console
If you want to play with the console, you can start with this:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Enter command (quit to exit):");
String input = keyboard.nextLine();
if(input != null) {
System.out.println("Your input is : " + input);
if ("quit".equals(input)) {
System.out.println("Exit programm");
exit = true;
} else if ("x".equals(input)) {
//Do something
}
}
}
keyboard.close();
}
}
Simply run ScannerTest and type any text, followed by 'enter'
Listen for key press in .NET console app
Use Console.KeyAvailable
so that you only call ReadKey
when you know it won't block:
Console.WriteLine("Press ESC to stop");
do {
while (! Console.KeyAvailable) {
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
How to handle key press event in console application
For console application you can do this, the do while
loop runs untill you press x
public class Program
{
public static void Main()
{
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
Console.WriteLine(keyinfo.Key + " was pressed");
}
while (keyinfo.Key != ConsoleKey.X);
}
}
This will only work if your console application has focus. If you want to gather system wide key press events you can use windows hooks
Related Topics
Xcode 3.2.1 and C++ String Fails!
What Is Default Storage Class for Global Variables
Drawing in a Win32 Console on C++
What Is the Cin Analougus of Scanf Formatted Input
Load Resource as Byte Array Programmaticaly in C++
Forward Declaration & Circular Dependency
C++ 128/256-Bit Fixed Size Integer Types
How to Implement an Function Equivalent to Bwmorph Matlab Function in Opencv
Is It Allowed to Cast Away Const on a Const-Defined Object as Long as It Is Not Actually Modified
How Many Decimal Places Does the Primitive Float and Double Support
With C++, I Get Pointer with 0Xcdcdcdcd When Creating a Class - What Is Happening
Inconsistent Use of Const Qualifier Between Declaration and Definition
Why Does Glgetstring(Gl_Version) Return Null/Zero Instead of the Opengl Version
Mapping Elements in 2D Upper Triangle and Lower Triangle to Linear Structure
C++ Class Member Function Callback
How to Iterate Over Two Vectors Simultaneously Using Boost_Foreach