简体   繁体   English

SetCurrentConsoleFontEx 使文本加粗

[英]SetCurrentConsoleFontEx for Making Text Bold

I'm trying to make a function (in C++) that uses the WinAPI to make something that resembles a "header" in the console.我正在尝试创建一个函数(在 C++ 中),它使用 WinAPI 在控制台中创建类似于“标题”的东西。 By "header," I simply want the text to be another color and bold.通过“标题”,我只是希望文本是另一种颜色和粗体。 I'm able to change the color, but bolding the text is proving frustrating.我可以更改颜色,但加粗文本令人沮丧。

I've read mixed answers about making text bold using the SetCurrentConsoleFontEx() ;我读过关于使用SetCurrentConsoleFontEx()将文本加粗的混合答案; some people say it's possible while others have said it's not (in a not very straightforward way).有些人说这是可能的,而另一些人则说不可能(以一种不太直接的方式)。 I came across a comment on this question that said bolding and color change can be applied to an individual character.我在这个问题上看到一条评论,说粗体颜色变化可以应用于单个字符。

Here's what I'm trying.这就是我正在尝试的。 This code is simplified, of course.当然,这段代码是简化的。

auto errormsg = []() { std::cout << "\nError!\n" << std::endl; };

HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_FONT_INFOEX font_info = { sizeof(font_info) };

try
{
    if (!GetCurrentConsoleFontEx(h, false, &font_info)) throw;
    auto old_font = font_info;

    font_info.FontWeight = FW_BOLD;
    if (!SetCurrentConsoleFontEx(h, false, &font_info)) throw;

    if (!SetConsoleTextAttribute(h, /* A short for color ID */)) throw;

    std::cout << /* Header text here */ << std::endl;

    // Restore old font and old font color...
}
catch (...)
{
    errormsg();
    exit(1);
}

Although I'm using C++ functionality here, I'm okay with a pure C solution;虽然我在这里使用 C++ 功能,但我对纯 C 解决方案没问题; I prefer whatever is simplest, of course.当然,我更喜欢最简单的。

Edit编辑
To clarify, the problem is when I restore the old font stuff, the entire console window is reverted back.澄清一下,问题是当我恢复旧字体时,整个控制台窗口都恢复了。 I obviously don't want this to happen.我显然不希望这种情况发生。

This is the default behavior of the console.这是控制台的默认行为。

If you want to support bold fonts by different in the console window, you may need to submit the feedback via feedback hub.如果您想在控制台窗口中支持不同的粗体字体,您可能需要通过反馈中心提交反馈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM