Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...