簡體   English   中英

為什么控制台在使用 function system() 后無法捕獲鼠標事件?

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

當我使用 function system() 時,我無法捕捉到任何鼠標事件。 我已經知道 system() function 是一個 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 重置許多控制台標志。 在每個“系統”之后,您應該以這種方式恢復控制台選項:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM