在Windows控制台中获取按键 [英] Get key press in windows console

查看:447
本文介绍了在Windows控制台中获取按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了这段代码

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;
}

使用方式:

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

我能够获得数字,字母甚至返回键。但是无法获取转义或其他功能键,例如控制键,alt。

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?

推荐答案

如果类似control和alt键之类的东西,这些是虚拟键击,是否可以修改它来检测这些键? ,它们是字符的补充。您将需要使用 ReadConsoleInput 。但是您将获得全部,鼠标也一样。因此,您确实需要从调用中过滤并返回一个结构,以便知道它是否类似于ctrl-A Alt-A。

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函数

INPUT_RECORD结构

KEY_EVENT_RECORD结构

虚拟键代码

这篇关于在Windows控制台中获取按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆