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();
     }
      }
   }

 

时间: 2024-10-04 10:18:45

C#更改控制台文本的前景色和背景色的相关文章

photoshop前景色和背景色工具

今天有同学不清楚前景色和背景色,写了篇简单教程: 在工具栏的下方有一个设置前景色和背景色的区域,如图: 1.前景色介绍 前景色图标表示油漆桶.画笔.铅笔.文字工具和吸管工具在图像中拖动时所用的颜色. 2.背景色介绍 在前景色图标下方的就是背景色,背景色表示橡皮擦工具所表示的颜色,简单说背景色就是纸张的颜色,前景色就是画笔画出的颜色. 3.切换颜色 用鼠标单击切换图标,或使用快捷键"J" . 4.默认颜色 用鼠标单击默认颜色图标,即恢复为前景色白色,背景色黑色.快捷键"D&qu

《网页美工设计Photoshop+Flash+Dreamweaver从入门到精通》——2.2 设置前景色和背景色

2.2 设置前景色和背景色 网页美工设计Photoshop+Flash+Dreamweaver从入门到精通 在Photoshop CC中,默认的前景色为黑色.背景色为白色.当设置了其他颜色后要恢复默认的颜色时,只需单击工具箱中的默认前景色和背景色按钮,如图2-18所示. 前景色:用于显示和选取当前绘图工具所使用的颜色.单击"前景色"按钮,可以打开"拾色器"对话框并从中选取颜色,如图2-19所示. 背景色:用于显示和选取图像的底色.选取背景色后,并不会改变图像的背景色

ASP.net 2.0 学习之001:鼠标移过GridView的行,前景色和背景色发生变化

asp.net 1.右击"GridView ",选择"属性"--"事件",选择"数据"下的"RowDataBound "属性,双击它. 2.在"GridView1_RowDataBound "方法下加入下列代码: if (e.Row.RowType == DataControlRowType.DataRow)...{      //鼠标移动到每项时颜色交替效果   e.Row.Attri

[转]scite文本编辑器的说明

scite,也就是SCIntilla based Text Editor, 基于SCIntilla编辑组件的文本编辑器.我们见到的许多文本编辑器都是基于SCIntilla编辑组件的. yidabu.com经过比较发现,同样是基于SCIntilla的文本编辑器,scite的功能最为强大. scite可以干什么呢? 程序员可以用scite来写代码,一般人可以用scite来写文章.这篇文章就是用scite来写的. scite是功能非常强大的text文本编辑器,正是因为其强大,所以其配置选项非常多,令初

MFC绘图基础 .

from:http://blog.csdn.net/leolee82/article/details/6992590 先认识一下MFC中的一些和绘图有关的结构体和类 1.点 (1)点结构POINT点数据结构POINT用来表示一点的x.y坐标: typedef struct tagPOINT { LONG x; LONG y; } POINT; (2)点类CPoint 点类CPoint为一个没有基类的独立类,封装了POINT结构,有成员变量x和y 其构造函数有5种: CPoint( ); CPoi

WM_CTLCOLOR消息 .

参考文章:白乔原创:VC之美化界面篇         在每个控件开始绘制之前,都会向其父窗口发送WM_CTLCOLOR通告消息,在该消息的处理函数中,可以设置控件显示文本的前景色.背景色以及字体.该消息处理函数还要求返回一个画刷的句柄,用于在控件具体的绘制之前擦除其客户区.         WM_CTLCOLOR映射消息处理函数为afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor).    常用代码为: [cpp] vie

如何更改音量条和亮度条颜色的背景色和前景色

默认情况下系统显示音量条和亮度条颜色为黑白色 用户想要更改为其它颜色,比如红黑颜色 操作步骤: 1.右键点击桌面,点击屏幕分辨率,然后点击高级设置; 2. 选择屏幕显示,点击前景色或者背景色,选择自己所需颜色; 5.选择所需颜色后,确定即可.

.NET Core的日志[2]:将日志输出到控制台

对于一个控制台应用,比如采用控制台应用作为宿主的ASP.NET Core应用,我们可以将记录的日志直接输出到控制台上.针对控制台的Logger是一个类型为ConsoleLogger的对象,ConsoleLogger对应的LoggerProvider类型为ConsoleLoggerProvider,这两个类型都定义在 NuGet包"Microsoft.Extensions.Logging.Console"之中. 本文已经同步到<ASP.NET Core框架揭秘>之中] 目录

C# 如何更改注视//字体的颜色?

问题描述 C#如何更改注视//字体的颜色? 解决方案 解决方案二:工具->选项->环境->字体和颜色,在显示项里找注释,然后修改项的前景色和背景色解决方案三:vs菜单->工具(tools)->选项(options)->文本编辑器(texteditor)->...里面去找解决方案四:引用2楼u012948520的回复: vs菜单->工具(tools)->选项(options)->文本编辑器(texteditor)->...里面去找 看来我误导