为什么控制台在使用函数 system() 后无法捕获鼠标事件?

Why console cannot catch mouse event after using function system()?

当我使用函数system()时,我无法捕捉到任何鼠标事件。 我已经知道 system() 函数是一个 shell 命令,但为什么使用此命令会阻止捕获鼠标事件?

#include <windows.h>
#include <stdio.h>
int main()
{
    HANDLE ConsoleWin;
    INPUT_RECORD eventMsg;
    DWORD Pointer;
    //system("mode con cols=140 lines=40"); //after using this function,I cannot catch any mouse event
    while (1)
    {
        ConsoleWin = GetStdHandle(STD_INPUT_HANDLE);//Get the console window
        ReadConsoleInput(ConsoleWin, &eventMsg, 1, &Pointer);//Read input msg
        if (eventMsg.EventType == MOUSE_EVENT && eventMsg.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) {
            printf("Left button clicked.");
        }
        else if (eventMsg.EventType == MOUSE_EVENT && eventMsg.Event.MouseEvent.dwButtonState == RIGHTMOST_BUTTON_PRESSED) {
            printf("Right button clicked.");
        }
    }
    return 0;
}

system() 执行新的 cmd.exe 重置许多控制台标志。在每个 "system" 之后,您应该以这种方式恢复控制台选项:

DWORD mode;
GetConsoleMode(ConsoleWin, &mode);
system("...your command...");
SetConsoleMode(ConsoleWin, mode);

顺便说一句,即使没有执行任何system(),您的程序也可能有同样的问题。它依赖于默认控制台设置,而默认控制台设置又取决于系统设置和用户首选项。我建议您在程序的开头添加此代码:

DWORD mode;
GetConsoleMode(ConsoleWin, &mode);
mode |= ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS;
SetConsoleMode(ConsoleWin, mode);