簡體   English   中英

關閉控制台時防止應用程序關閉

[英]Prevent application from closing when closing console

我有一個WinAPI / Win32應用程序,該應用程序還在打開主窗口之前也打開了一個控制台窗口(出於調試目的)。 我添加了一個安全檢查,以便在按下主窗口的X按鈕時詢問“您確定嗎?” 事情。 但是,如果我在控制台上單擊X,它將立即終止該應用程序,而不會發生任何問題。 有什么辦法可以防止這種情況? 這是我的代碼片段:

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR args, int nCmdShow)
{
EnableDebug();
WNDCLASSA MainWindow = { 0 };
MainWindow.hbrBackground = (HBRUSH) COLOR_WINDOW;
MainWindow.hCursor = LoadCursor(NULL, IDC_ARROW);
MainWindow.hInstance = hInst;
MainWindow.lpszClassName = "WindowClass";
MainWindow.lpfnWndProc = WndProc;
ATOM result = RegisterClassA(&MainWindow);
if (!result)
{
    MessageBoxA(NULL, "Failed to register window class", "Error", MB_OK);
    return -1;
}
MSG msg = { 0 };
//here the app goes on


 //here is the start of the debug function
    void EnableDebug(){
    if (AllocConsole() == 0)
    {
        MessageBoxA(NULL, "Unable to create a debug window!", "Error", MB_OK);
        return;
    }
    freopen("CONOUT$", "w", stderr);
    SetConsoleTitleA("Debug Window");
    clog.clear();

我相信您需要調用SetConsoleCtrlHandler以提供一個處理程序例程來處理close事件。 像這樣:

BOOL WINAPI MyCtrlHandler (DWORD dwCtrlType)
{
    if (dwCtrlType == CTRL_CLOSE_EVENT)
        ...
}

SetConsoleCtrlHandler (MyCtrlHandler, TRUE);

您可能想以各種方式處理dwCtrlType各種值。 有關詳細信息,請查閱文檔

您可以禁用控制台窗口的關閉按鈕 ,以防止意外終止應用程序:

if( HWND hwnd = GetConsoleWindow() )
{
    if( HMENU hMenu = GetSystemMenu( hwnd, FALSE ) )
    {
        EnableMenuItem( hMenu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED );
    }
}

暫無
暫無

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

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