Ler em inglês

Compartilhar via


Console.BackgroundColor Propriedade

Definição

Obtém ou define a cor da tela de fundo do console.

[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static ConsoleColor BackgroundColor { get; set; }
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static ConsoleColor BackgroundColor { get; set; }
public static ConsoleColor BackgroundColor { get; set; }

Valor da propriedade

ConsoleColor

Um valor que especifica a cor da tela de fundo do console; ou seja, a cor exibida atrás de cada caractere. O padrão é preto.

Atributos

Exceções

A cor especificada em uma operação de conjuntos não é um membro válido de ConsoleColor.

O usuário não tem permissão para executar essa ação.

Ocorreu um erro de E/S.

Exemplos

O exemplo a seguir salva os valores da ConsoleColor enumeração em uma matriz e armazena os valores atuais das BackgroundColor Propriedades e ForegroundColor para variáveis. Em seguida, ele altera a cor do primeiro plano para cada cor na ConsoleColor enumeração, exceto a cor que corresponde ao plano de fundo atual e altera a cor do plano de fundo para cada cor na ConsoleColor enumeração, exceto a cor que corresponde ao primeiro plano atual. (Se a cor do primeiro plano for igual à cor do plano de fundo, o texto não será visível.) Por fim, ele chama o ResetColor método para restaurar as cores originais do console.

using System;

class Example
{
   public static void Main()
   {
      // Get an array with the values of ConsoleColor enumeration members.
      ConsoleColor[] colors = (ConsoleColor[]) ConsoleColor.GetValues(typeof(ConsoleColor));
      // Save the current background and foreground colors.
      ConsoleColor currentBackground = Console.BackgroundColor;
      ConsoleColor currentForeground = Console.ForegroundColor;

      // Display all foreground colors except the one that matches the background.
      Console.WriteLine("All the foreground colors except {0}, the background color:",
                        currentBackground);
      foreach (var color in colors) {
         if (color == currentBackground) continue;

         Console.ForegroundColor = color;
         Console.WriteLine("   The foreground color is {0}.", color);
      }
      Console.WriteLine();
      // Restore the foreground color.
      Console.ForegroundColor = currentForeground;

      // Display each background color except the one that matches the current foreground color.
      Console.WriteLine("All the background colors except {0}, the foreground color:",
                        currentForeground);
      foreach (var color in colors) {
         if (color == currentForeground) continue;

         Console.BackgroundColor = color;
         Console.WriteLine("   The background color is {0}.", color);
      }

      // Restore the original console colors.
      Console.ResetColor();
      Console.WriteLine("\nOriginal colors restored...");
   }
}
//The example displays output like the following:
//    All the foreground colors except DarkCyan, the background color:
//       The foreground color is Black.
//       The foreground color is DarkBlue.
//       The foreground color is DarkGreen.
//       The foreground color is DarkRed.
//       The foreground color is DarkMagenta.
//       The foreground color is DarkYellow.
//       The foreground color is Gray.
//       The foreground color is DarkGray.
//       The foreground color is Blue.
//       The foreground color is Green.
//       The foreground color is Cyan.
//       The foreground color is Red.
//       The foreground color is Magenta.
//       The foreground color is Yellow.
//       The foreground color is White.
//
//    All the background colors except White, the foreground color:
//       The background color is Black.
//       The background color is DarkBlue.
//       The background color is DarkGreen.
//       The background color is DarkCyan.
//       The background color is DarkRed.
//       The background color is DarkMagenta.
//       The background color is DarkYellow.
//       The background color is Gray.
//       The background color is DarkGray.
//       The background color is Blue.
//       The background color is Green.
//       The background color is Cyan.
//       The background color is Red.
//       The background color is Magenta.
//       The background color is Yellow.
//
//    Original colors restored...

Comentários

Uma alteração na BackgroundColor propriedade afeta apenas a saída gravada em células de caracteres individuais após a alteração da cor do plano de fundo. Para alterar a cor do plano de fundo da janela do console como um todo, defina a BackgroundColor propriedade e chame o Clear método. O exemplo a seguir ilustra esse cenário.

using System;

public class Example
{
   public static void Main()
   {
      WriteCharacterStrings(1, 26, true);
      Console.MoveBufferArea(0, Console.CursorTop - 10, 30, 1,
                             Console.CursorLeft, Console.CursorTop + 1);
      Console.CursorTop = Console.CursorTop + 3;
      Console.WriteLine("Press any key...");
      Console.ReadKey();

      Console.Clear();
      WriteCharacterStrings(1, 26, false);
   }

   private static void WriteCharacterStrings(int start, int end,
                                             bool changeColor)
   {
      for (int ctr = start; ctr <= end; ctr++) {
         if (changeColor)
            Console.BackgroundColor = (ConsoleColor) ((ctr - 1) % 16);

         Console.WriteLine(new String((char)(ctr + 64), 30));
      }
   }
}

uma operação get para um aplicativo baseado em Windows, no qual um console não existe, retorna ConsoleColor.Black . Os sistemas Unix não fornecem nenhum mecanismo geral para buscar as cores de console atuais. Por isso, BackgroundColor retorna (ConsoleColor)-1 até que seja definido de forma explícita (usando o setter).

Aplica-se a