c++windowswinapiconsolewindows-11

How to change console size on Windows 11?


I wrote a code that reduces the size of console. But this doesn't work on Windows 11, using Visual Studio 2022 Community:

#include <iostream>
#include <Windows.h>

using namespace std;

int main(void)
{
    system("mode con cols=62 lines=34");

    return 0;
}

Actually, it worked in Windows 10.

Is this a Windows 11 problem, or is there any other way?

I also tried this one:

#include <Windows.h>
#include <iostream>

using namespace std;

void SetConsoleSize(int width, int height)
{
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    
    COORD bufferSize = { (SHORT)width, (SHORT)height };
    if (!SetConsoleScreenBufferSize(hOut, bufferSize))
    {
        std::cerr << "Buffer Fail" << std::endl;
    }
    
    SMALL_RECT windowSize = { 0, 0, (SHORT)(width - 1), (SHORT)(height - 1) };
    if (!SetConsoleWindowInfo(hOut, TRUE, &windowSize))
    {
        std::cerr << "Size Fail" << std::endl;
    }
}

int main(void)
{
    SetConsoleSize(100, 50);

    cin.get();

    return 0;
}

Is there a solution to solve this problem, or any other way to set the console size?


Solution

  • The default terminals of Windows 10 and Windows 11 are different, which is the reason for your problem.

    You can use SetWindowPos to resize any window as long as you provide the correct HWND.

        HWND hwnd = GetConsoleWindow();
        Sleep(10);//If you execute these code immediately after the program starts, you must wait here for a short period of time, otherwise GetWindow will fail. I speculate that it may be because the console has not been fully initialized.
        HWND owner = GetWindow(hwnd, GW_OWNER);
        if (owner == NULL) {
            // Windows 10
            SetWindowPos(hwnd, nullptr, 0, 0, 500, 500, SWP_NOZORDER|SWP_NOMOVE);
        }
        else {
            // Windows 11
            SetWindowPos(owner, nullptr, 0, 0, 500, 500, SWP_NOZORDER|SWP_NOMOVE);
        }
    

    It should be noted that SetWindowPos is affected by DPI awareness.