Reputation:
So I recently started learning C#, and I'm struggling to change background color of a console to a hex value. Here is my code:
using System;
namespace MyFisrtC_App
{
class Program
{
static void Main(string[] args)
{
ConsoleColor BGColor = ConsoleColor.White;
ConsoleColor FGColor = ConsoleColor.Black;
Console.Title = "Dumb App";
Console.BackgroundColor = BGColor;
Console.ForegroundColor = FGColor;
Console.Clear();
Console.WriteLine("This is just a simple dumb app. There is nothing special about it.");
Console.ReadKey();
}
}
}
Also if you know how to change font in C# that would be pretty cool.
Upvotes: 1
Views: 3102
Reputation: 216
This is unfortunately not possible due to the restriction of the Console API.
But you can for example calculate the nearest color to one that exist in the API.
static ConsoleColor ClosestConsoleColor(byte r, byte g, byte b)
{
ConsoleColor ret = 0;
double rr = r, gg = g, bb = b, delta = double.MaxValue;
foreach (ConsoleColor cc in Enum.GetValues(typeof(ConsoleColor)))
{
var n = Enum.GetName(typeof(ConsoleColor), cc);
var c = System.Drawing.Color.FromName(n == "DarkYellow" ? "Orange" : n); // bug fix
var t = Math.Pow(c.R - rr, 2.0) + Math.Pow(c.G - gg, 2.0) + Math.Pow(c.B - bb, 2.0);
if (t == 0.0)
return cc;
if (t < delta)
{
delta = t;
ret = cc;
}
}
return ret;
}
This is from: https://stackoverflow.com/a/12340136/10315352 credits all to @Glenn
Upvotes: 5
Reputation: 787
ConsoleColour is an enum which essentially is a list of numbers with defined names. So you can do the below to convert a number to a color
int number = 7;
ConsoleColor colour = (ConsoleColor)number;
If you want to do it from hex use the below
string hex = "0A";
int number = Convert.ToInt32(hex, 16);
ConsoleColor colour = (ConsoleColor)number;
You just need to make sure the number doesnt fall outside of the length of the enum, for example
if(number < Enum.GetValues<ConsoleColor>().Length -1 && number >= 0)
{
Console.ForeGroundColor = (ConsoleColor)number;
}
Upvotes: 0
Reputation: 1052
using System;
namespace TestCSharp
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("background red and text white");
Console.ResetColor();
Console.WriteLine("Color reset");
Console.ReadKey();
}
}
}
you can't use hex value, you can use these color:
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White
Upvotes: -1