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); ...
随机推荐
- Table of Contents - jBPM
Getting Started jBPM Installer Eclipse 安装 jBPM 插件 jBPM Core
- Android使用JNI(从java调用本地函数)
当编写一个混合有本地C代码和Java的应用程序时,需要使用Java本地接口(JNI)作为连接桥梁.JNI作为一个软件层和API,允许使用本地代码调用Java对象的方法,同时也允许在Java方法中调用本 ...
- Android高手进阶:Adapter深入理解与优化
一般是针对包含多个元素的View,如ListView,GridView,ExpandableListview,的时候我们是给其设置一个Adapter.Adapter是与View之间提供数据的桥梁,也是 ...
- C#调用SSIS包及读取DataReader目标
C#调用SSIS包需要引用两个DLL .(具体位置在C盘搜索,MSDN和百度提供的路径都不太正确) Microsoft.SQLServer.ManagedDTS.dll Microsoft.SqlSe ...
- sql_查询select
sql_查询select /****** Script for SelectTopNRows command from SSMS ******/ [r_gonghao] ,[r_mingzi] , ...
- dicom格式文件 界定标识符的处理
转自:http://www.cnblogs.com/assassinx/archive/2013/05/18/3084854.html 说到底无非几个事情 :1传输语法确定 2数据元素读取 3 7fe ...
- 利用word2vec对关键词进行聚类
1.收集预料 自己写个爬虫去收集网页上的数据. 使用别人提供好的数据http://www.sogou.com/labs/dl/ca.html 2.对预料进行去噪和分词 我们需要content其中的值, ...
- AOJ 0121 Seven Puzzle
7 パズル 7 パズルは 8 つの正方形のカードとこれらのカードがぴたりと収まる枠で構成されています.それぞれのカードには.互いに区別できるように 0, 1, 2, ..., 7 と番号がつけられてい ...
- 【风马一族_Android】android的新发现
Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW");这一段句话.可以调用出系统 ...
- Android:自定义控件样式(Selector)
前言 在开发一个应用程序过程中不可避免的要去修改组件的样式,比如按钮.输入框等.现在就看下如何通过Seletor实现样式的自定义.先看下简单的效果对比