Posted By

Rick on 11/16/13


Tagged

console color


Versions (?)

Different colors in console string


 / Published in: C#
 

This is way to get different fg and bg colors inside 1 string. You provide escape like characters to define colors.

This is a fg of #rRed #xand now we're back to normal. This is a bg of $bBlue#x and now we're back to normal. I can combine fg & bg#r$bcolors #xalso.

  1. class RPGConsole
  2. {
  3. public static Dictionary<char, ConsoleColor> Colors;
  4. public static char SpecialFGChar { get; set; }
  5. public static char SpecialBGChar { get; set; }
  6. public static char ResetChar { get; set; }
  7.  
  8. static RPGConsole()
  9. {
  10. Colors = new Dictionary<char, ConsoleColor>();
  11.  
  12. // set some defaults
  13. SpecialFGChar = '#';
  14. SpecialBGChar = '$';
  15. ResetChar = 'x';
  16.  
  17. // add some default colors
  18. Colors.Add('r', ConsoleColor.Red);
  19. Colors.Add('y', ConsoleColor.Yellow);
  20. Colors.Add('g', ConsoleColor.Green);
  21. Colors.Add('b', ConsoleColor.Blue);
  22. Colors.Add('w', ConsoleColor.White);
  23. }
  24.  
  25. public static void WriteLine(string value)
  26. {
  27. Write(value);
  28.  
  29. Console.Write(Environment.NewLine);
  30. }
  31.  
  32. private static bool SetFGColor(char value)
  33. {
  34. // look at the next char and make sure we have the color code registered
  35. if (Colors.ContainsKey(value))
  36. {
  37. Console.ForegroundColor = Colors[value];
  38.  
  39. return true;
  40. }
  41. else if (value == ResetChar)
  42. {
  43. Console.ResetColor();
  44.  
  45. return true;
  46. }
  47.  
  48. return false;
  49. }
  50.  
  51. private static bool SetBGColor(char value)
  52. {
  53. // look at the next char and make sure we have the color code registered
  54. if (Colors.ContainsKey(value))
  55. {
  56. Console.BackgroundColor = Colors[value];
  57.  
  58. return true;
  59. }
  60. else if (value == ResetChar)
  61. {
  62. Console.ResetColor();
  63.  
  64. return true;
  65. }
  66.  
  67. return false;
  68. }
  69.  
  70. // we call foreground switching twice so that the order of defining bg & fg doesn't matter in the string
  71. public static void Write(string value)
  72. {
  73. char[] letters = value.ToCharArray();
  74.  
  75. for (int i = 0; i < letters.Count(); i++)
  76. {
  77. // switch foreground color
  78. if (letters[i] == SpecialFGChar)
  79. {
  80. if (SetFGColor(letters[i + 1]))
  81. i += 2;
  82. }
  83.  
  84. // switch background color
  85. if (letters[i] == SpecialBGChar)
  86. {
  87. if (SetBGColor(letters[i + 1]))
  88. i += 2;
  89. }
  90.  
  91. // switch foreground color
  92. if (letters[i] == SpecialFGChar)
  93. {
  94. if (SetFGColor(letters[i + 1]))
  95. i += 2;
  96. }
  97.  
  98. Console.Write(letters[i]);
  99. }
  100. }
  101. }

Report this snippet  

You need to login to post a comment.