C++ Console Keyboard Events

C++ console keyboard events

You can use GetKeyState or GetAsyncKeyState, but that won't give you keydown/keyup events. It will only tell you what keys are currently down.

So if you really need to get the keydown/keyup events, you could install a hook.
A Console window has a window handle that is owned by code in Windows and a message pump, also owned by code in Windows.

You can get the window handle of of the console window by using GetConsoleWindowThen install a WH_CALLWNDPROC hook using SetWindowsHookEx to listen in on messages send to the console window.

You might try a WH_MSGFILTER hook instead. I don't know if this works for console windows, but it would generate less messages to be ignored if it does work.

Continuous keyboard input in C

There is a function called kbhit() or _kbhit it is in the <conio.h> library it returns true or false depending whether a key was hit. So you can go with something like this:

while (1){
if ( _kbhit() )
key_code = _getch();
// do stuff depending on key_code
else
continue;

Also use getch() or _getch which reads a character directly from the console and not from the buffer. You can read more about conio.h functions here they might be very useful for what you want to do.

Note: conio.h is not a standard library and implementations may vary from compiler to compiler.

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

How to handle key press events in C++

You won't find anything in the standard library for that. It's all platform-dependent. In Windows, you have functions like GetAsyncKeyState to get the state of a key on the keyboard for example.

SDL and SFML both have platform-independent event handling.

SDL2 cannot capture console keyboard events?

Unless you want to read keyboard input from stdin you need to open a window and focus it to get key events in SDL. Here's an example (note the call to SDL_Init uses SDL_INIT_VIDEO and there's some code in there for rendering a background and handling resize events).

#include <iostream>
#include <SDL2/SDL.h>

int main(int argc, char** argv)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0) { // also initialises the events subsystem
std::cout << "Failed to init SDL.\n";
return -1;
}

SDL_Window *window = SDL_CreateWindow(
"Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
680, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

if(!window) {
std::cout << "Failed to create window.\n";
return -1;
}

// Create renderer and select the color for drawing.
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 200, 200, 200, 255);

while(true)
{
// Clear the entire screen and present.
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);

SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT) {
SDL_Quit();
return 0;
}

if(event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
int width = event.window.data1;
int height = event.window.data2;
std::cout << "resize event: " << width << "," << height << std::endl;
}
}

if (event.type == SDL_KEYDOWN) {
int key = event.key.keysym.sym;
if (key == SDLK_ESCAPE) {
SDL_Quit();
return 0;
}

std::cout << "key event: " << key << std::endl;
}
}
}

return 0;
}

Key events are sent to the currently focused window and SDL uses the underlying OS to handle this. E.g. In Linux this means SDL calls X11 functions.

edit:
As detailed in this question it appears you can also get a snapshot of the state of the keys. In either case I think a window needs to be opened to receive events even though I've edited this multiple times to come to that conclusion (apologies if that caused any confusion). Your OS may provide functions for polling the state of the keyboard without using events or windows, such as GetAsyncKeyState in Windows.

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!

C# console key press event

You should use ReadKey method (msdn):

Console.Write("Press Y to start the game.");

char theKey = Console.ReadKey().KeyChar;

if (theKey == 'y' || theKey == 'Y')
{
Console.Clear();
Console.Write("Hello");
Console.ReadKey();
}
else
Console.Write("Error");

The return value of ReadKey method is ConsoleKey enum so you can use it in the if condition:

Console.Write("Press Y to start the game.");

ConsoleKey consoleKey = Console.ReadKey().Key;

if (consoleKey == ConsoleKey.Y)
{
Console.Clear();
Console.Write("Hello");
Console.ReadKey();
}
else
Console.Write("Error");

C# .NET Console Application getting keyboard input

The trick is that you first need to check if there is a KeyAvailable in the cache, and then use ReadKey() to read it. After that, your code should work as you expect. The line of code that does this would look something like:

// Check if there's a key available. If not, just continue to wait.
if (Console.KeyAvailable) { var key = Console.ReadKey(); }

Here's a sample to demonstrate:

public static void Main(string[] args)
{
Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2);
Console.CursorVisible = false;
Console.Write('*');

var random = new Random();

while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);

switch (key.Key)
{
case ConsoleKey.UpArrow:
if (Console.CursorTop > 0)
{
Console.SetCursorPosition(Console.CursorLeft - 1,
Console.CursorTop - 1);
Console.Write('*');
}
break;
case ConsoleKey.DownArrow:
if (Console.CursorTop < Console.BufferHeight)
{
Console.SetCursorPosition(Console.CursorLeft - 1,
Console.CursorTop + 1);
Console.Write('*');
}
break;
case ConsoleKey.LeftArrow:
if (Console.CursorLeft > 1)
{
Console.SetCursorPosition(Console.CursorLeft - 2,
Console.CursorTop);
Console.Write('*');
}
break;
case ConsoleKey.RightArrow:
if (Console.CursorLeft < Console.WindowWidth - 1)
{
Console.Write('*');
}
break;
}
}

// This method should be called on every iteration,
// and the iterations should not wait for a key to be pressed
// Instead of Frame.Update(), change the foreground color every three seconds
if (DateTime.Now.Second % 3 == 0)
Console.ForegroundColor = (ConsoleColor) random.Next(0, 16);
}
}


Related Topics



Leave a reply



Submit