Reputation: 791
I am writing a small console application in c# and I want to use the arrow keys to navigate through my menu. To make the selected option visible to the user I want to highlight it with a white background and black text but only the word and not the whole line.
I tried to position the cursor at the beginning of the word so only the word would be highlighted but it did not work. Could someone put me on the right direction, please?
for (int i = 0; i < filesArray.Length; i++)
{
Console.WriteLine();
if (i == 0)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Program.WriteAtTheMiddleOfTheScreen(filesArray[0]);
Console.ResetColor();
}
else
{
Program.WriteAtTheMiddleOfTheScreen(filesArray[i]);
}
}
Console.WriteLine();
Program.WriteAtTheMiddleOfTheScreen("Exit Program");
Console.SetCursorPosition((Console.WindowWidth/2)-filesArray[0].Length+2, 2);
That is what I want to achieve
public static void WriteAtTheMiddleOfTheScreen(string message)
{
message = String.Format("{0," + ((Console.WindowWidth / 2) + (message.Length / 2)) + "}", message);
Console.WriteLine(message);
}
Upvotes: 1
Views: 3578
Reputation: 61993
The Console
class supports two properties called ForegroundColor
and BackgroundColor
.
See MSDN: System.Console.ForegroundColor and MSDN: System.Console.BackgroundColor
(Hint: using Microsoft Visual Studio, you can place the cursor on Console
and hit Ctrl+Space to get a list of all properties offered by Console
.)
You can set these properties using members of the System.ConsoleColor
enumeration which contains members such as White
, Blue
, etc.
So, you set the BackgroundColor
property to some color, do your System.Console.Write()
, then set BackgroundColor
to something else, and so on.
Keep in mind that spaces are painted with the background color, so to prevent areas of the screen from being painted with unwanted background color, refrain from setting the BackgroundColor
property to an unwanted value and writing spaces there.
Upvotes: 3
Reputation: 310
This will help
for (int i = 0; i < 100; i++)
{
Console.WriteLine();
string Text = "MAP" + i;
Console.SetCursorPosition((Console.WindowWidth - Text.Length) / 2, Console.CursorTop);
if (i == 0)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine(Text);
Console.ResetColor();
}
else
{
Console.WriteLine(Text);
}
}
Upvotes: 0
Reputation: 369
C# Console Color Tutorial This page has all you need to change the color of console application.
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
The above code will change the background and foreground color of the console.
Upvotes: 0