如何获得当前控制台背景和文本颜色
how to get current console background and text colors?
我知道如何设置它们(SetConsoleTextAttribute),但没有GetConsoleTextAttribute来检索此信息。在未受影响的主机上,它应该是int 7。
问题是,当退出设置文本颜色的程序时,它在给定窗口运行的时间内保持不变,并且我不能假设用户没有将颜色设置为他自定义的喜欢。
对wincon.h
的快速grep显示CONSOLE_SCREEN_BUFFER_INFO
有一个wAttributes
成员,其文档记录为"由WriteFile和WriteConsole函数写入屏幕缓冲区的字符属性,或由ReadFile和ReadConsole函数回显到屏幕缓冲区的字符属性"。这与SetConsoleTextAttribute
的描述相匹配:"设置由WriteFile或WriteConsole函数写入控制台屏幕缓冲区的字符的属性,或由ReadFile或ReadConsole函数返回。"结构由GetConsoleScreenBufferInfo
返回。
感谢Talent25,我制作了这个函数:
#include <Windows.h>
bool GetColor(short &ret){
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
return false;
ret = info.wAttributes;
return true;
}
使用它:GetColor(CurrentColor);
CurrentColor -输出颜色数量的变量(背景* 16 +主色)。返回值通知操作是否成功。
下面是代码片段
HANDLE m_hConsole;
WORD m_currentConsoleAttr;
CONSOLE_SCREEN_BUFFER_INFO csbi;
//retrieve and save the current attributes
m_hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
if(GetConsoleScreenBufferInfo(m_hConsole, &csbi))
m_currentConsoleAttr = csbi.wAttributes;
//change the attribute to what you like
SetConsoleTextAttribute (
m_hConsole,
FOREGROUND_RED |
FOREGROUND_GREEN);
//set the ttribute to the original one
SetConsoleTextAttribute (
m_hConsole,
m_currentConsoleAttr);
相关文章:
- 通过样式表仅在QTabWidget中应用文本颜色一个特定选项卡
- 控制台中文本颜色异常
- 文本颜色 QPlainTextEdit QT
- 更改悬停在Gtkbutton的文本颜色
- 如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色
- 设置子窗口的文本颜色
- 更改数组中元素的文本颜色
- 尝试选择文本颜色
- MFC Rich编辑控件2.0文本颜色
- 无法更改 Visual Studio 2010 中输出的文本颜色和文本背景
- 使用 conio.h 更改文本颜色时出错
- Mouseover SDL2时更改文本颜色
- 为qlineedit设置了背景图像时,如何在qlineedit中设置文本颜色
- 如何从qplaintExtedIt获取文本颜色
- 自定义图形列表视图项目不更改文本颜色
- 直接在.png加载的cimage上绘制时,将文本颜色设置为
- 静态文本颜色
- QMenu:为特定 QAction 设置文本颜色
- 如何更改代码块中的文本颜色和控制台颜色
- Win32:设置富编辑的默认字体和文本颜色