首页 > 解决方案 > SetConsoleDisplayMode() 函数无法将我的窗口设置为全屏

问题描述

我有这些全局变量:

//width and height of the window
int WIDTH = GetSystemMetrics(SM_CXSCREEN);
int HEIGHT = GetSystemMetrics(SM_CYSCREEN);
//width and height of one character, font dimensions
constexpr int dW = 8, dH = 8;

我正在尝试创建一个 ASCII 引擎,这是设置窗口的功能,它只在程序开始时使用一次。

//set the font
    CONSOLE_FONT_INFOEX cf = {0};
    cf.cbSize = sizeof cf;
    cf.dwFontSize.X = dW;
    cf.dwFontSize.Y = dH;
    wcscpy(cf.FaceName, L"Terminal");
    SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), 0, &cf);

    HWND console = GetConsoleWindow();
    RECT ConsoleRect;
    GetWindowRect(console, &ConsoleRect);
    HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hstdout, &csbi);

//set the window
//fullscreen and remove vertical bar
    csbi.dwSize.X = csbi.dwMaximumWindowSize.X;
    csbi.dwSize.Y = csbi.dwMaximumWindowSize.Y;
    SetConsoleScreenBufferSize(hstdout, csbi.dwSize);
    MoveWindow(console, 0, 0, WIDTH, HEIGHT, TRUE);
    SetConsoleDisplayMode(hstdout, CONSOLE_FULLSCREEN_MODE, 0);
    ShowScrollBar(console, SB_BOTH, FALSE);

在我的代码工作之前,但我改变了一些小东西,我在窗口控制台设置中改变了一些东西,现在它不起作用。

如果这很重要,我正在使用 Visual Studio。

标签: c++windows

解决方案


我不是铁杆 Windows 程序员,但 SetConsoleDisplayMode() 并非所有地方都支持,您可以通过调用 GetLastError(); 来检查它是否有效。

要打开最大化控制台,您可以在下面尝试我的代码。
如果你真的想让你的代码在每个 Windows 函数调用之后调用 GetLastError ,那么某处可能存在错误。

hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

auto check_error = [](bool state, const std::string& msg) {
    if (!state) {
        auto error = GetLastError();
        std::cerr << msg << ' ' << error << std::endl;
    }
};

short font_size = 4;
CONSOLE_FONT_INFOEX cfi{ .cbSize = sizeof(cfi), .nFont = 0,
    .dwFontSize = {font_size, font_size}, 
    .FontFamily = FF_DONTCARE,
    .FontWeight = FW_NORMAL};

wcscpy_s(cfi.FaceName, L"Consolas");
bool state = SetCurrentConsoleFontEx(hConsole, false, &cfi);
check_error(state, "Set Console font error");

COORD coord = GetLargestConsoleWindowSize(hConsole);
screenWidth = coord.X * font_size;
screenHeight = coord.Y * font_size;

HWND console = GetConsoleWindow();
state = MoveWindow(console, 0, 0, screenWidth, screenHeight,  TRUE);
check_error(state, "Move console error");
state = ShowScrollBar(console, SB_BOTH, FALSE);
check_error(state, "Show scroll bar error");

推荐阅读