5

I found this piece of code online:

CHAR getch() {
    DWORD mode, cc;
    HANDLE h = GetStdHandle( STD_INPUT_HANDLE );

    if (h == NULL) {
        return 0; // console not found
    }

    GetConsoleMode( h, &mode );
    SetConsoleMode( h, mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT) );
    TCHAR c = 0;
    ReadConsole( h, &c, 1, &cc, NULL );
    SetConsoleMode( h, mode );
    return c;
}

Using it like:

while(1) {
    TCHAR key = getch();
}

I am able to get numeric, alphabetic even return key presses. But am not able to get escape or other functional keys like control, alt. Is it possible to modify it to detect also these keys?

drescherjm
  • 10,365
  • 5
  • 44
  • 64
user1806687
  • 934
  • 1
  • 10
  • 27

3 Answers3

12

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

lakeweb
  • 1,859
  • 2
  • 16
  • 21
0

The following code captures any key press. It is used to return from a function.

Documentation:

https://learn.microsoft.com/en-us/windows/console/readconsoleinput?redirectedfrom=MSDN

https://learn.microsoft.com/en-us/windows/console/input-record-str?redirectedfrom=MSDN

https://learn.microsoft.com/en-us/windows/console/key-event-record-str?redirectedfrom=MSDN

Purpose The function does some calculations, the progress of which are shown to the user on the console. When all is done the user wishes to return from the function. She does that by pressing any key. In all my other applications the user can return with the Esc key, so it is nice to have that work also here.

It works by allocating the console and setting handles for output from and input to the console. Flags OKflg_out and OKflg_in are set to verify the operations at the end. The for (; ;)-loop after the message "Press any key." to the user ends when the user presses a key.

The numerical code for the pressed key is (((irec.Event).KeyEvent).uChar).AsciiChar, but it is not used here. It could of course be used as a return code to determine the following actions in the calling function.

#include <windows.h>
// Various other includes.
void wrintf0(HANDLE stdOut, unsigned char *message)
{
    DWORD written=0;
    WriteConsoleA(stdOut, message, strleni(message), &written, NULL);
}
#define wrintf(message) wrintf0(stdOut,message)
// Various code lines.
void Myfunction(void)
{
    unsigned char OKflg_in=0,OKflg_out=0;
    HANDLE stdIn,stdOut;
    // Various code lines.
    AllocConsole();
    stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    if (stdOut != NULL && stdOut != INVALID_HANDLE_VALUE)
    {
        OKflg_out = 1;
        stdIn = GetStdHandle(STD_INPUT_HANDLE);
        if (stdIn != NULL && stdIn != INVALID_HANDLE_VALUE) OKflg_in = 1;
    }
    // Various code lines.
    if (OKflg_out)
    {
        if (OKflg_in)
        {
          DWORD cc;
          INPUT_RECORD irec;
          wrintf("Press any key.");
          for(; ;) {
              ReadConsoleInput(stdIn, &irec, 1, &cc );
              if (irec.EventType == KEY_EVENT && ((irec.Event).KeyEvent).bKeyDown) break;
          }
          CloseHandle(stdIn);
        }
        CloseHandle(stdOut);
    }
    FreeConsole();
    return;
}
  • 1
    [A code-only answer is not high quality](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Muhammad Mohsin Khan Apr 03 '22 at 22:36
-2

you have a lot of ways to get the keyboard inputs

you can use GetAsyncKeyState https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms646293(v=vs.85).aspx or GetKeyState https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms646301.aspx

which are far better than getch

RomMer
  • 113
  • 12
  • 3
    These are for GUI applications, not for console applications. The results you are going to get are not going to be synchronized with the state of the console input buffer. – Matteo Italia Dec 18 '16 at 21:55
  • 1
    You are going to get characters, you are not going to get them synchronized with the console input functions, Win32 stdin and CRT stdin (and with `GetAsyncKeyState` you aren't even going to get them synchronized with the thread's input queue). This has subtle implications, so unless you understand them fully you should avoid this stuff. – Matteo Italia Jan 12 '17 at 16:29