简体   繁体   中英

Get any key from keyboard in C++ including keys like control

I'm programming in C++ and have run into a wall.

I need to get input from the keyboard. The problem is that I also need to get input from keys like control, scroll lock, windows key, etc. I also need to be able to differentiate between the numpad and regular numbers 0-9.

I tried using _getch(). While it can get keys like arrow keys and the numpad, I can't get keys like control, shift and scroll lock.

Does anyone have any suggestions?

There is no standard way to do this because C++ does not assume the system even has all those things.

A good solution for what you are trying to do is the SDL library. Look here: https://www.libsdl.org/

I see the word "windows key" so I'm assuming you're programming for Windows

Use WinAPI ReadConsoleInput

HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD ir;
DWORD read;
if (!ReadConsoleInput(hInput, &ir, 1, &read) || read == 0) {
    // Something went wrong
}
if (ir.EventType == KEY_EVENT) {
    // Do stuff here
}

Refer to KEY_EVENT_RECORD for more information. You can get control keys states from

ir.Event.KeyEvent.dwControlKeyState

This is an example provided by Microsoft.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM