你需要在 WM_DESTROY
消息中使用 FreeConsole
销毁控制台。通常我会在一个包装了我的控制台的类中完成这个操作。这样可以在构造函数中将输入/输出重定向到控制台,在析构函数中重置输入/输出以及分别分配/销毁控制台。
然而,如果不使用类或任何包装器,可以按照以下方式完成。。。
示例:
#include <windows.h>
#include <streambuf>
#include <fstream>
#include <iostream>
std::streambuf *CinBuffer, *CoutBuffer, *CerrBuffer;
std::fstream ConsoleInput, ConsoleOutput, ConsoleError;
void RedirectIO()
{
CinBuffer = std::cin.rdbuf();
CoutBuffer = std::cout.rdbuf();
CerrBuffer = std::cerr.rdbuf();
ConsoleInput.open("CONIN$", std::ios::in);
ConsoleOutput.open("CONOUT$", std::ios::out);
ConsoleError.open("CONOUT$", std::ios::out);
std::cin.rdbuf(ConsoleInput.rdbuf());
std::cout.rdbuf(ConsoleOutput.rdbuf());
std::cerr.rdbuf(ConsoleError.rdbuf());
}
void ResetIO()
{
ConsoleInput.close();
ConsoleOutput.close();
ConsoleError.close();
std::cin.rdbuf(CinBuffer);
std::cout.rdbuf(CoutBuffer);
std::cerr.rdbuf(CerrBuffer);
CinBuffer = NULL;
CoutBuffer = NULL;
CerrBuffer = NULL;
}
LRESULT __stdcall WindowProcedure(HWND Hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case WM_CREATE:
AllocConsole();
RedirectIO();
std::cout<<"HELLO CONSOLE!"<<std::endl;
break;
case WM_DESTROY:
std::cout<<"BYE-BYE CONSOLE!"<<std::endl;
ResetIO();
FreeConsole();
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(Hwnd, Msg, wParam, lParam);
}
return 0;
};
int main()
{
WNDCLASSEX WndClass =
{
sizeof(WNDCLASSEX), CS_DBLCLKS, WindowProcedure,
0, 0, GetModuleHandle(NULL), LoadIcon(NULL, IDI_APPLICATION),
LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW + 1),
NULL, "WindowClass", LoadIcon (NULL, IDI_APPLICATION)
};
if(RegisterClassEx(&WndClass))
{
HWND WindowHandle = CreateWindowEx(0, "WindowClass", "Window Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 500, NULL, NULL, GetModuleHandle(NULL), NULL);
if(WindowHandle)
{
MSG msg = {NULL};
ShowWindow(WindowHandle, SW_SHOWDEFAULT);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
}
CloseWindow()
应该是用于最小化窗口的(请查看文档),它是一个来自黑暗时代的古老函数,而且它的命名非常糟糕/令人困惑。如果你想模拟按下窗口的 X 按钮,则需要向窗口发送WM_CLOSE
消息。 - pasztorpisti