关键字: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();}}}

转载于:https://www.cnblogs.com/lanzhi/p/6468059.html

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

  1. css标签定义不可修改文本,推荐5个好用但却经常被忽略的css属性(禁止选中文本、更改选中文本的背景色、不用br换行、字体间距、隐藏滚动条)...

    01 禁用用户选中一个元素(element)的文本 使用属性user-select,并且将它的值设置为none,我们可以将一个元素的文本设置为不能被用户选中. element { -webkit-us ...

  2. 【c++】设置控制台窗口字体颜色和背景色(system和SetConsoleTextAttribute函数 )

    编译后弹出的黑框框(exe 可执行文件)总是黑底白字,在做实践大作业时想到尝试改变字体的颜色与背景色,搜索发现有system和SetConsoleTextAttribute两个函数,各有长处,详细了解 ...

  3. 【c++】设置控制台窗口字体颜色和背景色(system和SetConsoleTextAttribute函数 )(内含超好玩的c++游戏链接)

    目录 游戏推荐 研究初步 SetConsoleTextAttribute函数 原型 参数 举个栗子 最后 题外话 一篇游戏笔记... 游戏推荐 最近,在玩(完)一个c++的控制台游戏. 啊,真的非常好 ...

  4. Notepad++如何更改选中文字的颜色或背景色

    Notepad++是一款文字编辑利器,优点就不多说了,体积小巧功能强大,只是在界面自定义方面就不够人性化,只有几个简单的前景色.背景色.字体大小等设置. 解决问题的办法似乎很简单,将选中文字的背景颜色 ...

  5. Notepad用html怎么选颜色,Notepad++如何更改选中文字的颜色或背景色

    Notepad++如何更改选中文字的颜色或背景色 发布时间:2021-01-05 14:06:52 来源:亿速云 阅读:190 作者:小新 小编给大家分享一下Notepad++如何更改选中文字的颜色或 ...

  6. 计算机画图设计前景色,画图的前景色和背景色

    在关于画图程序的教材中,有关前景色和背景色是一笔带过.如书中叙述:前景色--图画的颜色,单击鼠标左键选取所需颜色:背景色--图画的底色,单击鼠标右键选取所需颜色.这让我们对前景色和背景色的理解比较模糊 ...

  7. input文本框自动填充背景色黄色解决办法

    文章目录 input文本框自动填充背景色黄色解决方式 解决前后,截图对比: 解决方式 兼容性说明 input文本框自动填充背景色黄色解决方式 如何取消黄背景色?浏览器兼容处理? 解决前后,截图对比: ...

  8. 前景色和背景色_好色之人福利 — 室内空间背景色

    影响背景色的因素 空间界面上运用的材质不同,其图案.质感.肌理也就不尽相同,这些都是影响背景色的因素. 1.肌理影响背景色 两个几乎相同的颜色,只是它们表现在不同的材料表面,不难看出,越是粗糙的表面, ...

  9. photoshop 图片裁剪与填充前景色及背景色

    有时候根据需求,需要对图形做一些预处理,为避免处理后的图形属性(包括像素等)发生改变,这里选用 Photoshop 进行处理.处理图文步骤如下: 1.可一次选择多个图片文件(此处选择4个) 2.选择左 ...

最新文章

  1. 贼好用的 Java 工具类库
  2. [MOSS 译]如何:在WEB内容查询部件中使用自定义的字段
  3. linux调试crontab,linux - crontab 的调试,启动thin服务器
  4. XnView v1.93.6 Final 注册机
  5. linux中兴上网客户端,中兴新支点N-Print,简单高效Linux桌面操作系统网络打印方案...
  6. empinfo Oracle数据库,Oracle:其他数据库对象
  7. sql python 教程_Python SQLAlchemy ORM教程(3)
  8. a12处理器怎么样_iPhone运行安卓系统卡成翔,苹果A系处理器彻底跌落神坛!
  9. 计算机培训中学语文研修计划,初中语文个人研修计划书
  10. mysql sql语句 编辑器_三个非常实用的开源SQL编辑器
  11. 粒子群优化算法matlab实现,粒子群优化算法的MATLAB程序实现+源程序
  12. 如何在程序中调用Bartender软件打印文件模板
  13. 视觉目标跟踪算法收集-实时更新
  14. 支付宝支付加密规则梳理,写的太好了!
  15. 如何打开控制面板(windows10)
  16. git pull时遇到的问题
  17. python repl_Python自学第二天 REPL+基础语法
  18. Git SSH 方式无法 push 踩坑
  19. 华为机试题python版节选(基础编程题)
  20. coursera 吴恩达四卷积神经网络第四周 Art Generation with Neural Style Transfer

热门文章

  1. 数据分析真的很火吗?真的有很多企业需要这样的岗位吗?求大佬指点。
  2. php7使用curl扩展
  3. 艾永亮:2020年微信的进化方向
  4. 数据分析实战 205 :项目分析思路 —— 某在线教育机构经营分析
  5. 总是显示观战服务器请求失败,观战服务器数据请求失败
  6. vue2和veu3的区别
  7. linux until循环,linux命令:until循环
  8. Python练习题答案: 格式化像“巴特,莉萨和玛吉”名称的字符串。【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战
  9. Redis - 高性能 + 高并发
  10. Wireshark捕获分析TCP数据包三次握手