diff --git a/PowerKit/Extensions/ConsoleExtensions.cs b/PowerKit/Extensions/ConsoleExtensions.cs new file mode 100644 index 0000000..6a4c38d --- /dev/null +++ b/PowerKit/Extensions/ConsoleExtensions.cs @@ -0,0 +1,40 @@ +using System; + +namespace PowerKit.Extensions; + +internal static class ConsoleExtensions +{ + extension(Console) + { + /// + /// Temporarily changes the console foreground color and returns a handle that restores the original color when disposed. + /// + public static IDisposable WithForegroundColor(ConsoleColor color) + { + var lastColor = Console.ForegroundColor; + Console.ForegroundColor = color; + + return Disposable.Create(() => Console.ForegroundColor = lastColor); + } + + /// + /// Temporarily changes the console background color and returns a handle that restores the original color when disposed. + /// + public static IDisposable WithBackgroundColor(ConsoleColor color) + { + var lastColor = Console.BackgroundColor; + Console.BackgroundColor = color; + + return Disposable.Create(() => Console.BackgroundColor = lastColor); + } + + /// + /// Temporarily changes the console foreground and background colors and returns a handle that restores the original colors when disposed. + /// + public static IDisposable WithColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor) => + Disposable.Merge( + Console.WithForegroundColor(foregroundColor), + Console.WithBackgroundColor(backgroundColor) + ); + } +}