C#更改控制台文本颜色
C#更改控制台文本的前景色和背景色
关键字:C# NET 控制台 前景色 背景色
地址:http://www.cnblogs.com/txw1958/archive/2012/12/07/csharp-console-color.html
This step-by-step article describes how to change the foreground and background colors of the text that is written to the Console window by using Visual C#.
This article describes how to save the original settings of the Console window as the program starts, how to modify the color settings, and how to restore the colors to their original values as the program quits.
Introduction
To change the foreground and background colors of text that the Console window displays, use the SetConsoleTextAttributeWin32 application programming interface (API) function. This function sets the attributes of the characters that are written to the screen buffer.
When you change these attributes at run time, the changes are valid for as long as the Console window is open. If you close and reopen the Console window, the attributes are reset to their default values. If you execute the program from a command line in a Console window that is already running, changes that you make to the text attributes are valid for that Console window for as long as the window is open, even after your program quits. Therefore, an program should restore the original color attributes before the program quits.
You can obtain the text attributes of the Console window by using the GetConsoleScreenBufferInfo API function. This function fills an instance of the CONSOLE_SCREEN_BUFFER_INFO structure with information about the current output buffer settings. ThewAttribute parameter of this structure contains the color information that defines the foreground and background colors of the text. The possible colors are any color combination that can be created by combining red, green, and blue.
OriginalColors = ConsoleInfo.wAttributes;
SetConsoleTextAttribute(hConsoleHandle, color);
You can use the ResetColor method to reset the output buffer attributes of the Console window to the original values that are captured when the program begins its execution.
SetConsoleTextAttribute(hConsoleHandle, OriginalColors);
Step-by-Step Example
- In Visual Studio .NET or Visual Studio 2005, create an new Visual C# Console Application project.
- In Solution Explorer, right-click your project, click Add, and then select Add Class to add a new class to your program.
- Paste the following sample code in the class that is created. Verify that the sample code replaces all of existing the code in the class.

using System;
using System.Runtime.InteropServices; namespace ConsoleColor
{
/// Summary description for Class2.
public class Class2
{
private int hConsoleHandle;
private COORD ConsoleOutputLocation;
private CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
private int OriginalColors; private const int STD_OUTPUT_HANDLE = -11; [DllImport("kernel32.dll", EntryPoint="GetStdHandle", SetLastError=true,
CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", EntryPoint="GetConsoleScreenBufferInfo",
SetLastError=true, CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int GetConsoleScreenBufferInfo(int hConsoleOutput,
ref CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); [DllImport("kernel32.dll", EntryPoint="SetConsoleTextAttribute",
SetLastError=true, CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int SetConsoleTextAttribute(int hConsoleOutput,
int wAttributes); public enum Foreground
{
Blue = 0x00000001,
Green = 0x00000002,
Red = 0x00000004,
Intensity = 0x00000008
} public enum Background
{
Blue = 0x00000010,
Green = 0x00000020,
Red = 0x00000040,
Intensity = 0x00000080
} [StructLayout(LayoutKind.Sequential)] private struct COORD
{
short X;
short Y;
} [StructLayout(LayoutKind.Sequential)] private struct SMALL_RECT
{
short Left;
short Top;
short Right;
short Bottom;
} [StructLayout(LayoutKind.Sequential)] private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public int wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
} // Constructor.
public Class2()
{
ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
ConsoleOutputLocation = new COORD();
hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsoleHandle, ref ConsoleInfo);
OriginalColors = ConsoleInfo.wAttributes;
} public void TextColor(int color)
{
SetConsoleTextAttribute(hConsoleHandle, color);
} public void ResetColor()
{
SetConsoleTextAttribute(hConsoleHandle, OriginalColors);
}
}
}

4. Paste the following sample code in the class file that contains the Main function. Verify that the sample code replaces all of the existing code in the file.

using System; namespace ConsoleColor
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Class2 TextChange = new Class2();
Console.WriteLine("Original Colors");
Console.WriteLine("Press Enter to Begin");
Console.ReadLine();
TextChange.TextColor((int)Class2.Foreground.Green +
(int)Class2.Foreground.Intensity);
Console.WriteLine("THIS TEXT IS GREEN");
Console.WriteLine("Press Enter to change colors again");
Console.ReadLine();
TextChange.TextColor((int)Class2.Foreground.Red +
(int)Class2.Foreground.Blue +
(int)Class2.Foreground.Intensity);
Console.WriteLine("NOW THE TEXT IS PURPLE");
Console.WriteLine("Press Enter to change colors again");
Console.ReadLine();
TextChange.TextColor((int)Class2.Foreground.Blue +
(int)Class2.Foreground.Intensity +
(int)Class2.Background.Green +
(int)Class2.Background.Intensity);
Console.WriteLine("NOW THE TEXT IS BLUE AND BACKGROUND OF IT IS GREEN");
Console.WriteLine("Press Enter change everything back to normal");
Console.ReadLine();
TextChange.ResetColor();
Console.WriteLine("Back to Original Colors");
Console.WriteLine("Press Enter to Terminate");
Console.ReadLine();
}
}
}

C#更改控制台文本颜色的更多相关文章
- Linux终端和win32控制台文本颜色输出
在使用putty.secureCRT.XShell等终端仿真器连接linux系统时,ls.vim等工具的输出都含有各种颜色,这些颜色的输出大大地增强了文本的可读性. 通常我们可以使用echo命令加-e ...
- Qt 样式表鼠标滑过按钮更改Text文本颜色
QSS语法参考http://blog.csdn.net/liang19890820/article/details/51691212 Qt助手上也有比较详细的说明,选择器以及伪选择器,现在只是做个简单 ...
- C#更改控制台文本的前景色和背景色
关键字:C# NET 控制台 前景色 背景色地址:http://www.cnblogs.com/txw1958/archive/2012/12/07/csharp-console-color.html ...
- VC编程中如何设置对话框的背景颜色和静态文本颜色
晚上编一个小程序,涉及到如何设置对话框的背景颜色和静态文本颜色.这在VC6.0中本来是一句话就搞定的事.在应用程序类中的InitInstance()函数添加: //设置对话框背景和文本颜色 SetDi ...
- SetConsoleTextAttribute 函数--设置控制台文本属性
SetConsoleTextAttribute函数 来源:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs. ...
- 关于echart横轴颜色 纵轴颜色 以及文本颜色的修改
xAxis : [ { type : 'category', boundaryGap : false, data : ['周一','周二','周三','周四','周五','周六','周日'], axi ...
- 【css3】如何自定义 placeholder 文本颜色
昨天写了一篇基于 jquery 实现 ie 浏览器兼容 placeholder 效果,具体内容点击传送门.不过还是有点小瑕疵,就是不能设置 placeholder 文本颜色.本文主要介绍利用 css ...
- android:更改PagerTabStrip背景颜色,标题字体样式、颜色和图标,以及指示条的颜色
1.更改PagerTabStrip背景颜色 我们直接在布局中设置background属性可以: <android.support.v4.view.ViewPager android:id=&qu ...
- xamarin android 在代码中如何设置文本颜色
xamarin android 在代码中如何设置文本颜色 TextView v = FindViewById<TextView>(Android.Resource.Id.Message); ...
随机推荐
- PAT1028—— 人口普查
某城镇进行人口普查,得到了全体居民的生日.现请你写个程序,找出镇上最年长和最年轻的人. 这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过200岁的老人,而今天是2014年9月 ...
- ArrayList与List对象用法与区别
比如: 代码如下 复制代码 string[] s=new string[3];//赋值s[0]="a";s[1]="b";s[2]="c"; ...
- Nginx在嵌入式系统中的应用
-----------------本文转载自 http://blog.csdn.net/xteda/article/details/39708009 ------------------------- ...
- fpm打包redis3.0.7
1.安装redis tar -xf redis-3.0.7.tar.gz -C /usr/local cd /usr/local && mv redis-3.0.7 redis cd ...
- 使用inotify检测linux目录内文件变化
#include <unistd.h> #include <sys/inotify.h> #include <stdio.h> #include <error ...
- Linux5.8下安装PhpMyadmin无法关联php-mcrypt问题
一.yum安装php-mcrypt ##发现没办法安装 原来CentOS 官方默认不在对mcrypt模块 进行支持,所以必须另想办法折腾了2个小时总算搞定,这里主要使用了Fedora的扩展库, E ...
- 初测WIN10
WIN10已经发布,通过百度直通车把WIN7升级成了WIN10,改变较大,不太习惯,用着不是很顺手. 吐槽几个问题 1.微软的Visual Studio 2015 Community版本,宣布是免费的 ...
- UE4 将本地图片转成UTexture2D 在runtime显示
UFUNCTION(BlueprintCallable, Category = "TextureFromDisk") static class UTexture2D* GetTex ...
- JAVA多线程学习--生产者消费者问题
一.问题描述 生产者消费者问题是一个典型的线程同步问题.生产者生产商品放到容器中,容器有一定的容量(只能顺序放,先放后拿),消费者消费商品,当容器满了后,生产者等待,当容器为空时,消费者等待.当生产者 ...
- laravel--为什么属性在模型中没有定义,却取出来了值,这些属性哪里来的
看laravel模型中的这段代码, public function getLimitUsersAttribute() { return $this->user_limit - $this-> ...