Alex
Alex

Reputation: 876

PostMessage Not working with allocated console in winform app

SO I got a c++/cli form app which has a checkbox(debug in chinese) with the name of checkBox3 inside my app:

This is the code of the checkbox:

private: System::Void checkBox3_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
        //set the debug flag
        g.debug = !g.debug;
        HWND allocatedConsole = NULL;
        if (this->checkBox3->Checked == true)
        {
            AllocConsole();
            freopen("CONOUT$", "w", stdout);//use cout
        }
        else {
            allocatedConsole = GetConsoleWindow();
            std::cout << allocatedConsole << std::endl;
            PostMessageA(allocatedConsole, WM_CLOSE, 0, 0);
            FreeConsole();
        }
    }

Which does that whenever I click on the checkbox, it allocates a console and then when I un-check the checkbox, it stores the H-window of the console using GetConsoleWindow function inside allocatedConsole and then tries to close allocatedConsole remotely using the PostMessageA function with the WM_CLOSE message and finally it free's it.

However when I un-check the checkbox it free's the console but does not close it at all.

Thanks in advance.

Upvotes: 1

Views: 108

Answers (1)

catnip
catnip

Reputation: 25408

Try sending a WM_SYSCOMMAND message with wParam = SC_CLOSE. This more closely mimics selecting 'Close' from the system menu.

Upvotes: 3

Related Questions