Storing a colour in a variable for future use - c#

I am writing a bit of a dungeon crawler as I learn my way through c#. I am using visual studio and the application is a "Console App (.NET Framework)". My problem is that I have an option in the main menu to change text colour and I am trying to find away to make this change all the other times I change the colour so that it returns to a set default.
I have tried to assign the colour to a variable, lets say, default and then do the Console.ForegroundColor = ConsoleColor.default; I looked online everywhere and can't find a fix.
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
Console.ForgroundColor = Console.Color.White;
// This needs to be default ^^

You can create a property that will of ConsoleColor which will considered as a default color.
Just Assign it when ever you want default color should set to Console.ForegroundColor
Something like,
public class Program
{
public static ConsoleColor DefaultColor { get; set; } = ConsoleColor.Black;
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
//You can use DefaultColor whenever you want to assign default color to Foreground
Console.ForegroundColor = DefaultColor;
}
}

Related

How can I have a dynamic property in c#

I am creating a method that allows me to print a message in the console and to be able to change the color of the message in that same method.
I send 2 parameters to carry out this action, message (which is the message that is printed in the console) and color (which is the color that I want to be printed in the console)
I have my code like this:
public void Write(string message, string color = "White"){
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(message);
}
But I need ConsoleColor.White to grab my dynamic color as follows (similar to javascript): ConsoleColor [color];
How can I achieve this? Thanks in advance.
What I tried was the above: ConsoleColor[color];
ConsoleColor is an Enum, so the usual way to do this would be to take a ConsoleColor as the second parameter:
public void Write(string message, ConsoleColor color = ConsoleColor.White){
Console.ForegroundColor = color;
Console.WriteLine(message);
}
If you really need it to be a string, you can use Enum.Parse, but this runs the risk of a failed conversion if the caller passes an invalid color value:
public void Write(string message, string color = "White"){
Console.ForegroundColor = Enum.Parse<ConsoleColor>(color);
Console.WriteLine(message);
}
Or if you want a version that won't throw with a bad value:
public void Write(string message, string color = "White"){
Console.ForegroundColor = Enum.TryParse<ConsoleColor>(color, out ConsoleColor parsedColor)
? parsedColor : ConsoleColor.White;
Console.WriteLine(message);
}

How to pass color as parameter in c#?

I need to change font color many times in console app.
Instead of typing (or copying) each time :
Console.ForegroundColor = ConsoleColor.MyColor; in my code,
I want to type only
c(Red) or c(Yellow).
I thaough about something like this:
static void c(<???> myColor){
Console.ForegroundColor = ConsoleColor.MyColor;
}
How can I achieve that ?
Here is a method you can use to set the foreground color of your Console. I named the function as SetConsoleForeground but you can set it as you like such as c
/// <summary>
/// Sets Console Foreground color to the given color
/// </summary>
/// <param name="consoleColor">Foreground color to set</param>
private static void SetConsoleForeground Color(ConsoleColor consoleColor) {
Console.ForegroundColor = consoleColor;
}
Instead of passing c(Red) pass c(ConsoleColor.Red) and use parameter of type ConsoleColor enum in defination of method c()
public static void c(ConsoleColor myColor){
Console.ForegroundColor = myColor;
}
Call function using
c(ConsoleColor.Red);
MSDN ConsoleColor
I want to type only c(Red) or c(Yellow)
If you want to pass string called Red or Yellow and assign ForegroundColor to your console, then you can try below
public static void SetForegroundColor(string colorName)
{
//Set black as foreground color if TryParse fails to parse color string.
if(Enum.TryParse(ConsoleColor, colorName, out ConsoleColor color)
Console.ForegroundColor = color;
else
Console.ForegroundColor = ConsoleColor.Black;
}
Now you can pass color name as a string to this function, Like
SetForegroundColor("Red");
SetForegroundColor("Yello");
MSDN: Enum.TryPrase

Console Color Background Color Not Changing

I have a static method that I want to use to change the Console.BackgroundColor if it's running under the test environment. When I break on the line after the color is changed is is still set to Black.
public static void LogError(string err)
{
if (IsRunningFromMspec)
{
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.WriteLine(" &&&" + err);
}
else if (MyTracer.MyLevelSwitch.TraceError && !string.IsNullOrEmpty(err))
{
Trace.TraceError(" &&& - " + err);
}
}
Console.BackgroundColor does not change the background color of the whole console window. It only changes the background color of the text you will write after you set that color.
So your output Console.WriteLine(" &&&" + err); will now be written with a DarkRed background:
As Ian H. pointed out in the comments, to set the whole console window's background to the desired color call
Console.Clear();
after you changed the color. But of course this will delete all the content you previously wrote, which you perhaps don't want.

First time attempting programing. What am I doing wrong here?

enter image description hereFor my first try, I looked up some YouTube tutorials. One is showing how to create a Magic 8 Ball. I am following the instructions pretty much exactly but it won't work. When written like this it's fine:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
}
}
As you see I am trying to try create a String, not that I need one to do this. I just want to see how it works (So when I need it I don't need to re-type it and can just post this) But starting off it says "TellPeopleTheName must declare a body" I'm confused as this did not happen in the video. Not only that but when I cut and paste the code to join with it. For some reason it all breaks and no longer works:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
The entire bottom section is underlined in red saying "Invalid Token" and Writeline does not exist in this context". This confuses me more as this did not happen in the video either. What am I doing so wrong?
Thanks for the help and sorry for the nooby comments. I'm 20 and always wanted to learn coding but always been too busy working. Recently broke my back and now have plenty of time sitting doing nothing so I figured I would give it a shot.
This is mine (on top) and his (Bellow) and even after your help (I did go and re-watch and noticed I put String Void and not Static void) These problems still are here and I still don't understand. I apologise. I am really trying to learn and understand. This is a section I could skip and still make the 8-ball but I want to know why it does not work and how to fix it so then I know for when I do need to use this.
NEW FULL CODE:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
//This will tell people the name
static void TellPeopleTheName()
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
This line is out of place and doesn't actually do anything:
String Void TellPeopleTheName(String Text);
It's void, not Void. Casing matters.
You're giving it two return types, String and void. It either returns something or it doesn't.
That's a method header, but you're missing a method body. As a single line of code it doesn't make sense. Methods need to do something.
For example, a method might look like this:
void TellPeopleTheName(string text)
{
// write code in here to do something
}
Then you would invoke (call) that method somewhere from another method, when you want to perform that operation:
TellPeopleTheName("some text");
Or, in the case of a method which returns a string:
string TellPeopleTheName(string text)
{
// code which does something
return "some string";
}
Invoking it would be the same, but you could store the return value in a variable or otherwise use it in some way:
var someVariable = TellPeopleTheName("some text");
(Note: There are an ongoing variety of issues you may encounter even in trying what's described here. The difference between a static and non-static method come to mind, particularly if you try to call this from main(). Or the variety of ways you may return from a method or use the returned value. And so on. There's much to learn. Good luck!)
String Void TellPeopleTheName(String Text);
should be
void TellPeopleTheName(String Text)
{
}
That would take care of "missing body" error!
void should be in lowercase.
You are missing open/close brackets on the method too.
I notice a couple things you've missed in understanding.
What you've tried to do is write a method to write to the console the name of the program, but the method is not structured correctly.
The general structure of a method is...
AccessModifier static/non-static ReturnType MethodName (ParameterType ParameterName) {
//code to do something
}
An access modifier defines how accessible the method is to other code (as a starting programmer, just keep it as public until you become more advanced).
Putting static or nothing (non-static) is a little confusing for a beginner, if you'll be calling the method from Main (a static method) then it will need to be static, that's sufficient enough for a beginner's understanding for now.
The return type defines what the method should return back when the method is called.
The method name is just how the method is called, should be descriptive and clear what the method does.
A parameter type is the type of object that is being passed as a parameter for the method to use.
A parameter name is just a name, the name should easily explain what the parameter's purpose is for the method.
Following this structure, your method should look like...
public static void TellPeopleTheName(string text)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
If you want to make the method more "correct", then it would be...
public static void TellPeopleTheName(string nameOfProgram)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(nameOfProgram);
}
and you would call the method like this...
TellPeopleTheName("Magic 8 Ball. By: Conner Bostock");

Want to conditionally change Console foreground color based on input

I'm trying to make a KeyDown statement work. So I'm writing:
private void KeyDown(object sender, System.Windows.Forms.KeyEventArgs e);
System.Windows.Forms won't work I read that its a Visual Studio Code thing you have to go to Project.json and add System.Windows.Forms as a dependency. I don't know what to write to add it. I searched the web and searched stock overflow. I can't find anything.
I don't know what to type in to add it.
I could be wrong, but I don't believe you can use the System.Windows.Forms assembly with a .Net Core project. My Visual Studio is acting up so I wasn't able to try using it via the project.json imports feature. Having said that, it wouldn't provide you with what you want anyway.
Since you are wanting to capture the input from the user, via the console, and change the color based on some conditions - you'll have to do that manually yourself.
The following is a complete application example that shows how to do that. Essentially you have to evaluate each character entered into the console and determine if it's a number. If it is a number, you have to move the cursor back 1 position so you can overwrite the value that was just entered. Prior to overwriting the value, you change the consoles foreground color.
using System;
namespace ConsoleApp2
{
public class Program
{
public static void Main(string[] args)
{
// Set up an infinite loop that will allow us to forever type unless 'Q' is pressed.
while(true)
{
ConsoleKeyInfo pressedKey = Console.ReadKey();
// If Q is pressed, we quit the app by ending the loop.
if (pressedKey.Key == ConsoleKey.Q)
{
break;
}
// Handle the pressed key character.
OnKeyDown(pressedKey.KeyChar);
}
}
private static void OnKeyDown(char key)
{
int number;
// Try to parse the key into a number.
// If it fails to parse, then we abort and listen for the next key.
// It will fail if anything other than a number was entered since integers can only store whole numbers.
if (!int.TryParse(key.ToString(), out number))
{
return;
}
// If we get here, then the user entered a number.
// Apply our logic for handling numbers
ChangeColorOfPreviousCharacters(ConsoleColor.Green, key.ToString());
}
private static void ChangeColorOfPreviousCharacters(ConsoleColor color, string originalValue)
{
// Store the original foreground color of the text so we can revert back to it later.
ConsoleColor originalColor = Console.ForegroundColor;
// Move the cursor on the console to the left 1 character so we overwrite the character previously entered
// with a new character that has the updated foreground color applied.
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.ForegroundColor = color;
// Re-write the original character back out, now with the "Green" color.
Console.Write(originalValue);
// Reset the consoles foreground color back to what ever it was originally. In this case, white.
Console.ForegroundColor = originalColor;
}
}
}
The output to the console will look like this:

Categories

Resources