我正在制作一个必须无边界的控制台应用程序;为此,我更改了控制台窗口样式和窗口区域,如下所示。
在某些时候,我遇到了一个问题,它使控制台窗口的大小通常约为 2x1 个字符,或者有时完全出现错误(不可见的客户区、某些部分为白色、某些部分透明、随机边框等)。
有人告诉我,添加ShowWindow(hWnd, SW_HIDE);到它现在所在的行将解决问题。它做了。
现在我想弄清楚为什么问题首先存在,以及是否有其他方法可以防止它?
有人告诉我这个问题可能会发生,因为 Windows 试图在我的程序同时访问窗口属性(位置、样式、大小等)。不过,我不知道这是不是真的。
#include <Windows.h>
#include <iostream>
int main()
{
    HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
    SMALL_RECT srWnd = {0, 0, 1, 1};
    SetConsoleWindowInfo(hCon, 1, &srWnd);
    COORD cBuffSize = {81, 26};
    SetConsoleScreenBufferSize(hCon, cBuffSize);
    srWnd.Top = 0;
    srWnd.Right = 80;
    srWnd.Bottom = 25;
    srWnd.Left = 0;
    SetConsoleWindowInfo(hCon, 1, &srWnd);
    // When the next two lines are moved so that they are the first two lines inside main(), the window gets bugged.
    HWND hWnd = GetConsoleWindow();
    ShowWindow(hWnd, SW_HIDE); // Or if you just remove this line
    RECT rClnt;
    GetClientRect(hWnd, &rClnt);
    SetWindowLong(hWnd, GWL_STYLE, WS_POPUP);
    LONG exStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
    exStyle &= ~(WS_EX_CLIENTEDGE | WS_EX_APPWINDOW);
    SetWindowLongPtr(hWnd, GWL_EXSTYLE, exStyle | WS_EX_TOOLWINDOW);
    rClnt.right += 1;
    HRGN rgnClnt = CreateRectRgnIndirect(&rClnt);
    SetWindowRgn(hWnd, rgnClnt, 1);
    RECT rScrn;
    GetWindowRect(GetDesktopWindow(), &rScrn);
    SetWindowPos(hWnd, HWND_TOPMOST, rScrn.right / 2 - rClnt.right / 2, rScrn.bottom / 2 - rClnt.bottom / 2, 0, 0, SWP_NOSIZE | SWP_FRAMECHANGED);
    ShowWindow(hWnd, SW_SHOW);
    std::cin.get();
    return 0;
}