检测c++控制台中功能键

Detect function keys in c++ console.

本文关键字:功能键 控制台 c++ 检测      更新时间:2023-10-16

我想检测功能键,如f1保存f2刷新控制台使用c++,所以我可以添加进一步的功能。

检查这个例子:

#include <conio.h>
using namespace std;
int main()
{
    cout << "Press any key! CTRL-D to end" << endl;
    while(1)
    {
        unsigned char x = _getch();
        if (0 == x)
        {
            printf("Function key!n");
            x = _getch();
        }
        printf("key = %02xn", x);
        if (x == 4) break;
    }
    return 0;
}

当你按下功能键时,你会得到一个0,后面跟着另一个代码。使用该代码来确定您得到了哪个f键

如果您在windows控制台,您可以使用ReadConsoleInput()来检测和处理键盘事件。

所有键都映射为虚拟键。F功能键映射为VK_F1VK_F12

下面是控制台键盘处理的实现。

#include <stdio.h>
#include <windows.h>
#include <iostream>
using namespace std;

void save();
void refresh();

int main(){
    DWORD        mode;          /* Preserved console mode */
    INPUT_RECORD event;         /* Input event */
    BOOL         QUIT = FALSE;  /* Program termination flag */
    /* Get the console input handle */
    HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
    /* Preserve the original console mode */
    GetConsoleMode( hstdin, &mode );
    /* Set to no line-buffering, no echo, no special-key-processing */
    SetConsoleMode( hstdin, 0 );

    while (!QUIT){           

        if (WaitForSingleObject( hstdin, 0 ) == WAIT_OBJECT_0){  /* if kbhit */
            DWORD count;  /* ignored */
            /* Get the input event */
            ReadConsoleInput( hstdin, &event, 1, &count );
            cout<<"Key Code   = "<<event.Event.KeyEvent.wVirtualKeyCode <<" n";
        }
            /* Only respond to key release events */
            if ((event.EventType == KEY_EVENT)
            &&  !event.Event.KeyEvent.bKeyDown){        

                    switch (event.Event.KeyEvent.wVirtualKeyCode){
                        case VK_ESCAPE:
                           QUIT = TRUE;
                         break;

                        case VK_F1:
                                  save();
                         break;

                       case VK_F2:
                                  refresh();
                         break;

                       case VK_F5:
                         break;

                       case VK_F8:
                         break;

                    }//switch
                   event.Event.KeyEvent.wVirtualKeyCode=-1;             
        }
    }
 return 0; 
}

void save(){
}

void refresh(){
}

更多键映射:https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

F1-F12使用此解决方案可跨平台工作。

在Windows上,F11在命令提示符中切换全屏模式,因此不能被检测为按键。

试试这个:

#include <iostream>
#include <system.h>
int main(){
while(true){
Sleep(10);
if(GetKeyState('R') & 0x8000){
std::cout << "R Pressed";
}
}
return 0;
}