【问题标题】:Change console colors and keep the output in C++更改控制台颜色并将输出保留在 C++ 中
【发布时间】:2017-04-17 22:41:40
【问题描述】:

我需要制作一个类似于 Window 的 CMD 的 CLI。为了制作颜色命令,我在rlutil.h 中使用了rlutil::setColorrlutil::setBackgroundColor 函数。但是,要更改所有控制台中的颜色,我必须清除屏幕 (rlutil::cls()),否则只有新的输出才会出现这些更改,如图所示。

没有 cls:

使用 cls:

在cmd中(我使用@echo off 不显示当前目录):

这是我做的函数:

void colors(string value) {//I recive the user's input (like in the cmd)
    char foo[3];//I save each character in this array
    int c_text = 0, c_bg = 0;//Variables to get the numeric value of each character
    if(value.length() == 2) {//This is to only accept 2 characters as parameter for the command
        strcpy(foo, value.c_str());//Copy the values of the string in the array
        c_bg= chartoHEX(foo[0]);//Take the int value of each character 
        //(if the parameter in chartoHEX is '0', returns 0, if it's 'A', returns 10, and so on)
        c_text = chartoHEX(foo[1]);
        //If the function returns -1 means that the parameter wasn't an HEX number
        if(c_text != -1 && c_bg != -1) {
            rlutil::setColor(c_text);//Changes the text color
            rlutil::setBackgroundColor(c_bg);//Changes the background color
        }
    }
}

当我调用函数时:

colors("0a");
rlutil::cls();
cout << "C:\\Users\\Raven>";

更改颜色后如何保持输出?

【问题讨论】:

    标签: c++ windows cmd


    【解决方案1】:

    如果您使用低级本机 Windows 控制台功能,您可以更改颜色而不影响文本。使用GetStdHandle_get_osfhandle 获取控制台句柄,然后调用WriteConsoleOutputAttribute

    【讨论】:

    • 这不起作用,但这帮助我找到了解决方案,而不是使用WriteConsoleOutputAttribute,我使用了FillConsoleOutputAttribute。无论如何,谢谢。
    • @RavenH.- 在这里揭示解决方案怎么样?
    • FillConsoleOutputAttribute 用相同的颜色填充每个单元格,WriteConsoleOutputAttribute 指定数组中每个单元格的颜色。只需选择最适合您需求的功能即可。
    猜你喜欢
    • 2013-06-09
    • 2016-01-23
    • 2013-06-27
    • 1970-01-01
    • 2014-01-10
    • 2015-08-19
    • 2020-10-06
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多