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 = -; [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#更改控制台文本的前景色和背景色的更多相关文章
- C#更改控制台文本颜色
C#更改控制台文本的前景色和背景色 关键字:C# NET 控制台 前景色 背景色地址:http://www.cnblogs.com/txw1958/archive/2012/12/07/cshar ...
- VC++ 设置控件显示文本的前景色、背景色以及字体
在每个控件开始绘制之前,都会向其父窗口发送WM_CTLCOLOR通告消息,在该消息的处理函数中,可以设置控件显示文本的前景色.背景色以及字体.该消息处理函数还要求返回一个画刷的句柄,用于在控件具体的绘 ...
- Linux终端和win32控制台文本颜色输出
在使用putty.secureCRT.XShell等终端仿真器连接linux系统时,ls.vim等工具的输出都含有各种颜色,这些颜色的输出大大地增强了文本的可读性. 通常我们可以使用echo命令加-e ...
- css 前景色与背景色
前景色:color:#990000; 背景色:background-color:red; 可以用来设置文字的前景色与背景色 <!-- 作者:纤锐出处:http://www.cnblogs.com ...
- SetConsoleTextAttribute 函数--设置控制台文本属性
SetConsoleTextAttribute函数 来源:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs. ...
- wxWidgets:前景色与背景色
wxWidgets中有多个函数可以用来设定前景色和背景色,下面就来看看他们的用法区别: wxWindow::SetBackgroundColour(const wxColour &) 在你重绘 ...
- QTextEdit中选中文本修改字体与颜色,全部文本修改字体与颜色(设置调色板的前景色、背景色、文字颜色以及基色)
----我的生活,我的点点滴滴!! 当然以下内容都可以通过设置样式来达到目的,但是下面不使用这样的方法 先来看张图,理解此图基本就能实现上面所要达到的目的了 Widget::Widget(QWidge ...
- 使用API修改控制台输出的颜色(前景色和背景色)
1.api原型 SetConsoleTextAttribute BOOL WINAPI SetConsoleTextAttribute( _In_ HANDLE hConsoleOutput, // ...
- Qt Style Sheets Examples——定制前景色和背景色
例子取自:http://qt-project.org/doc/qt-4.8/stylesheet-examples.html 以lineEdit为例 (1)设置某个lineEdit的背景色为黄色 li ...
随机推荐
- 结合Wireshark捕获分组深入理解TCP/IP协议栈之HTTP协议
摘要: 本文简单介绍了Web应用层协议理论知识,详细讲述了HTTP请求报文和响应报文各个字段含义,并从Wireshark俘获分组中选取HTTP相关报文进行分析. 一.概述 Web的应用 ...
- fatal error C1859的有效解决办法
作者:朱金灿来源:http://blog.csdn.net/clever101 在服务器(操作系统为Widows Server2008)上使用VS C++2008编译工程,总是出现这样一个错误:fat ...
- 根据PID获取进程名&根据进程名获取PID
Liunx中 通过进程名查找进程PID可以通过 pidof [进程名] 来查找.反过来 ,相同通过PID查找进程名则没有相关命令.在linux根目录中,有一个/proc的VFS(虚拟文件系统),系统当 ...
- Visual Studio 项目目录下的bin目录和 obj目录
一.Bin目录 Visual Studio 编译时,在bin 目录下有debug 和 release 目录. 1.Debug: 通常称为调试版本,它包含调试信息,所以要比Release 版本大很多(可 ...
- 图形界面Aardio
用aardio给python写个图形界面 前阵子在用python写一些小程序,写完后就开始思考怎么给python程序配一个图形界面,毕竟控制台实在太丑陋了. 于是百度了下python的图形界面库,眼花 ...
- p2p网贷系统的架构设计
p2p网贷系统,标准版已经初步完成了. 最近写点总结,也算是分享吧. 简介:p2p网贷系统,是理财类的互联网金融系统.核心功能,就是理财人用户注册,冲钱,然后投标,标到期之后,收到回款.如果不想 ...
- 【47.95%】【codeforces 554C】Kyoya and Colored Balls
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- Spark源代码阅读笔记之DiskStore
Spark源代码阅读笔记之DiskStore BlockManager底层通过BlockStore来对数据进行实际的存储.BlockStore是一个抽象类,有三种实现:DiskStore(磁盘级别的持 ...
- PHP移动互联网开发笔记(8)——MySQL数据库基础回顾[2]
一.数据表 为了确保数据的完整性和一致性,在创建表时指定字段名称,字段类型和字段属性外,还需要使用约束(constraint),索引(index),主键(primary key)和外键(foregin ...
- 主从同步设置的重要参数log_slave_updates
说明:最近部署了mysql的集群环境,详细如下M01和M02为主主复制,M01和R01为主从复制:在测试的过程中发现了以下问题: 1.M01和M02的主主复制是没有问题的(从M01写入数据能同步到M0 ...