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. 从数据库里面取值绑定到Ztree

    1.效果图(思路:将数据库表按照一定的格式排序,然后序列化成json字符串,绑定到Ztree上并显示出来) zTree v3.5.16 API 文档 :http://www.ztree.me/v3/a ...

  2. 无限极分类sql数据库的设计

    --创建测试数据表tb ) , pid ) , name )) ' , null , '广东省') ' , '广州市') ' , '深圳市') ' , '天河区') ' , '罗湖区') ' , '福 ...

  3. DateDiff函数 asp运算时间

    DateDiff DateDiff函数 返回 返回 Variant (Long) 的值,表示两个指定日期间的时间间隔数目. 语法 DateDiff(interval, date1, date2[, f ...

  4. Swift 概述及Swift运算符和表达式

    Swift  是用于设计 iOS 及 Mac OS X 应用的一门新 语言. Swift 特点 •   Swift  保留了 C  与 Objective-C 的优点,并摒弃 其为了兼容 C  语言所 ...

  5. ios 中的block应用

    在这个大冬天里默默敲着键盘,勿喷.今天学习swift过程中,学习到闭包,发现闭包和oc的block中有很多的相同之处,又重新学习了一下并且学习了一些高级点的用法,内容如下: 1.block格式说明:( ...

  6. VxWorks 6.9 内核编程指导之读书笔记 -- Singnals

    Signals 信号是操作系统用于异常处理和异步控制流的关键.在很多方面,信号相当于软件方面的硬件中的中断.操作系统产生的信号包括总线错误和浮点处理异常.信号也提供了API来管理和产生信号.在应用程序 ...

  7. UI4_UIWebView

    // // ViewController.m // UI4_UIWebView // // Created by zhangxueming on 15/7/7. // Copyright (c) 20 ...

  8. Ant打jar包指定MainClass

    一般用ant打jar的时候不用指定程序的入口!这个jar一般是给其他app引用的. 但是如果该jar就是程序的启动jar.例如: java -jar abc.jar  这个时候需要指定jar的入口类! ...

  9. ZigBee profile

        每个ZigBee设备都与一个特定模板相关联,可能是公共模板或私有模板.这些模板定义了设备的应用环境.设备类型以及用于设备间通信的簇.采用公共模板,可以确保不同供应商的设备在相同应用领域的互操作 ...

  10. centos6.5下的mysql5.6.30安装

    1.解压mysql tar -xf mysql-5.6.30-linux-glibc2.5-x86_64.tar.gz  -C /usr/local mv mysql-5.6.30-linux-gli ...