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

  1. In Visual Studio .NET or Visual Studio 2005, create an new Visual C# Console Application project.
  2. In Solution Explorer, right-click your project, click Add, and then select Add Class to add a new class to your program.
  3. 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#更改控制台文本颜色的更多相关文章

  1. Linux终端和win32控制台文本颜色输出

    在使用putty.secureCRT.XShell等终端仿真器连接linux系统时,ls.vim等工具的输出都含有各种颜色,这些颜色的输出大大地增强了文本的可读性. 通常我们可以使用echo命令加-e ...

  2. Qt 样式表鼠标滑过按钮更改Text文本颜色

    QSS语法参考http://blog.csdn.net/liang19890820/article/details/51691212 Qt助手上也有比较详细的说明,选择器以及伪选择器,现在只是做个简单 ...

  3. C#更改控制台文本的前景色和背景色

    关键字:C# NET 控制台 前景色 背景色地址:http://www.cnblogs.com/txw1958/archive/2012/12/07/csharp-console-color.html ...

  4. VC编程中如何设置对话框的背景颜色和静态文本颜色

    晚上编一个小程序,涉及到如何设置对话框的背景颜色和静态文本颜色.这在VC6.0中本来是一句话就搞定的事.在应用程序类中的InitInstance()函数添加: //设置对话框背景和文本颜色 SetDi ...

  5. SetConsoleTextAttribute 函数--设置控制台文本属性

    SetConsoleTextAttribute函数 来源:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs. ...

  6. 关于echart横轴颜色 纵轴颜色 以及文本颜色的修改

    xAxis : [ { type : 'category', boundaryGap : false, data : ['周一','周二','周三','周四','周五','周六','周日'], axi ...

  7. 【css3】如何自定义 placeholder 文本颜色

    昨天写了一篇基于 jquery 实现 ie 浏览器兼容 placeholder 效果,具体内容点击传送门.不过还是有点小瑕疵,就是不能设置 placeholder 文本颜色.本文主要介绍利用 css ...

  8. android:更改PagerTabStrip背景颜色,标题字体样式、颜色和图标,以及指示条的颜色

    1.更改PagerTabStrip背景颜色 我们直接在布局中设置background属性可以: <android.support.v4.view.ViewPager android:id=&qu ...

  9. xamarin android 在代码中如何设置文本颜色

    xamarin android 在代码中如何设置文本颜色 TextView v = FindViewById<TextView>(Android.Resource.Id.Message); ...

随机推荐

  1. w3cschool关于list-style-position时的另外发现

    首先list-style-position有inside和outside... 另外发现:设置inline-block时 那个圆点消失了.. <!DOCTYPE html> <htm ...

  2. CSS里的引用@import、link

    引入CSS的方法有两种,一种是@import,一种是link @import url('地址');<link href="地址" rel="stylesheet&q ...

  3. C# 中 datagridview 绑定BindingList类型和更新

    C# 中的datagridview是一个非常有用且强大的控件,可以用来绑定数据库.绑定LIST类型的变量等等. 这里我们说一说绑定List类型并实时更新datagridview的情况.实时更新,指的是 ...

  4. WCF之安全

    传输安全. 点对点,对整个消息进行加密,性能损失,当中间者不安全时,消息也就不安全了. WCF中支持传输安全和消息安全模式. 通过配置和绑定来设置.<Security Mode =Transct ...

  5. (转)Yale CAS + .net Client 实现 SSO(3)

    第一部分:安装配置 Tomcat 第二部分:安装配置 CAS 第三部分:实现 ASP.NET WebForm Client 1. 下载.NET CAS client. .NET CAS Client ...

  6. hdu 1102 Constructing Roads Kruscal

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102 题意:这道题实际上和hdu 1242 Rescue 非常相似,改变了输入方式之后, 本题实际上更 ...

  7. 10+ powerful debugging tricks with Visual Studio

    10+ powerful debugging tricks with Visual Studio Original link : http://www.codeproject.com/Articles ...

  8. C++ 实现不能被继承的类

    方法一: #include <iostream> using namespace std; class A { public: static A* getInstance(); stati ...

  9. module graceful-fs for npm

    问题: 今天使用hexo时发现错误,hexo:command not found.于是重新安装hexo.但是在安装好npm后,却发现运行 npm 出现错误,没有找到模块graceful-fs,在纠结了 ...

  10. JAVA多线程学习--生产者消费者问题

    一.问题描述 生产者消费者问题是一个典型的线程同步问题.生产者生产商品放到容器中,容器有一定的容量(只能顺序放,先放后拿),消费者消费商品,当容器满了后,生产者等待,当容器为空时,消费者等待.当生产者 ...