Skip to content

Instantly share code, notes, and snippets.

@jsmarble
Created December 7, 2016 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsmarble/b12f8e9c8454588fec98d67688867f82 to your computer and use it in GitHub Desktop.
Save jsmarble/b12f8e9c8454588fec98d67688867f82 to your computer and use it in GitHub Desktop.
public class ConsoleColorContext : IDisposable
{
private ConsoleColor backupBackgroundColor;
private ConsoleColor backupForegroundColor;
private ConsoleColorContext()
{
this.backupForegroundColor = Console.ForegroundColor;
this.backupBackgroundColor = Console.BackgroundColor;
}
public ConsoleColorContext WithForeground(ConsoleColor foregroundColor)
{
Console.ForegroundColor = foregroundColor;
return this;
}
public ConsoleColorContext WithBackground(ConsoleColor backgroundColor)
{
Console.BackgroundColor = backgroundColor;
return this;
}
public ConsoleColorContext RestoreBackgroundTo(ConsoleColor backgroundColor)
{
this.backupBackgroundColor = backgroundColor;
return this;
}
public ConsoleColorContext RestoreForegroundTo(ConsoleColor foregroundColor)
{
this.backupForegroundColor = foregroundColor;
return this;
}
public void Dispose()
{
Console.ForegroundColor = backupForegroundColor;
Console.BackgroundColor = backupBackgroundColor;
}
public static ConsoleColorContext Create()
{
return new ConsoleColorContext();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment