为什么使用功能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;
}
keith_ye_mao 回答:为什么使用功能system()后控制台无法捕获鼠标事件?

system()执行一个新的cmd.exe,它将重置许多控制台标志。在每个“系统”之后,您应该通过以下方式还原控制台选项:

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);
本文链接:https://www.f2er.com/3104793.html

大家都在问