Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase Console

 

Publicado: octubre de 2016

Representa los flujos de entrada, salida y error estándar para las aplicaciones de consola. Esta clase no puede heredarse.

Para examinar el código fuente de .NET Framework de este tipo, consulte el origen de referencia.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)


public static class Console

NombreDescripción
System_CAPS_pubpropertySystem_CAPS_staticBackgroundColor

Obtiene o establece el color de fondo de la consola.

System_CAPS_pubpropertySystem_CAPS_staticBufferHeight

Obtiene o establece el alto del área del búfer.

System_CAPS_pubpropertySystem_CAPS_staticBufferWidth

Obtiene o establece el ancho del área del búfer.

System_CAPS_pubpropertySystem_CAPS_staticCapsLock

Obtiene un valor que indica si se activa o desactiva la alternancia de teclado de BLOQ MAYÚS.

System_CAPS_pubpropertySystem_CAPS_staticCursorLeft

Obtiene o establece la posición en columnas del cursor en el área del búfer.

System_CAPS_pubpropertySystem_CAPS_staticCursorSize

Obtiene o establece el alto del cursor en una celda de carácter.

System_CAPS_pubpropertySystem_CAPS_staticCursorTop

Obtiene o establece la posición en filas del cursor en el área del búfer.

System_CAPS_pubpropertySystem_CAPS_staticCursorVisible

Obtiene o establece un valor que indica si el cursor es visible.

System_CAPS_pubpropertySystem_CAPS_staticError

Obtiene el flujo de salida de error estándar.

System_CAPS_pubpropertySystem_CAPS_staticForegroundColor

Obtiene o establece el color de primer plano de la consola.

System_CAPS_pubpropertySystem_CAPS_staticIn

Obtiene el flujo de entrada estándar.

System_CAPS_pubpropertySystem_CAPS_staticInputEncoding

Obtiene o establece la codificación que usa la consola para leer la entrada.

System_CAPS_pubpropertySystem_CAPS_staticIsErrorRedirected

Obtiene un valor que indica si el flujo de salida de errores se ha redirigido desde el flujo de errores estándar.

System_CAPS_pubpropertySystem_CAPS_staticIsInputRedirected

Obtiene un valor que indica si la entrada se ha redirigido desde el flujo de entrada estándar.

System_CAPS_pubpropertySystem_CAPS_staticIsOutputRedirected

Obtiene un valor que indica si la salida se ha redirigido desde el flujo de salida estándar.

System_CAPS_pubpropertySystem_CAPS_staticKeyAvailable

Obtiene un valor que indica si hay disponible una acción de presionar una tecla en el flujo de entrada.

System_CAPS_pubpropertySystem_CAPS_staticLargestWindowHeight

Obtiene el máximo número posible de filas para la ventana de la consola, basado en la fuente y la resolución de pantalla actuales.

System_CAPS_pubpropertySystem_CAPS_staticLargestWindowWidth

Obtiene el máximo número posible de columnas para la ventana de la consola, basado en la fuente y la resolución de pantalla actuales.

System_CAPS_pubpropertySystem_CAPS_staticNumberLock

Obtiene un valor que indica si está activada o desactivada la alternancia de teclado de BLOQ NUM.

System_CAPS_pubpropertySystem_CAPS_staticOut

Obtiene el flujo de salida estándar.

System_CAPS_pubpropertySystem_CAPS_staticOutputEncoding

Obtiene o establece la codificación que usa la consola para escribir la salida.

System_CAPS_pubpropertySystem_CAPS_staticTitle

Obtiene o establece el título que se va a mostrar en la barra de título de la consola.

System_CAPS_pubpropertySystem_CAPS_staticTreatControlCAsInput

Obtiene o establece un valor que indica si la combinación de la tecla modificadora Control y de la tecla de consola C (Ctrl+C) se trata como una entrada ordinaria o como una interrupción controlada por el sistema operativo.

System_CAPS_pubpropertySystem_CAPS_staticWindowHeight

Obtiene o establece el alto del área de la ventana de la consola.

System_CAPS_pubpropertySystem_CAPS_staticWindowLeft

Obtiene o establece la posición más a la izquierda del área de la ventana de la consola con respecto al búfer de pantalla.

System_CAPS_pubpropertySystem_CAPS_staticWindowTop

Obtiene o establece la posición superior del área de la ventana de la consola con respecto al búfer de pantalla.

System_CAPS_pubpropertySystem_CAPS_staticWindowWidth

Obtiene o establece el ancho de la ventana de la consola.

NombreDescripción
System_CAPS_pubmethodSystem_CAPS_staticBeep()

Reproduce el sonido de un bip a través del altavoz de la consola.

System_CAPS_pubmethodSystem_CAPS_staticBeep(Int32, Int32)

Reproduce el sonido de un bip con una frecuencia y duración especificadas a través del altavoz de la consola.

System_CAPS_pubmethodSystem_CAPS_staticClear()

Borra la información que se muestra en el búfer de pantalla y en la correspondiente ventana de la consola.

System_CAPS_pubmethodSystem_CAPS_staticMoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32)

Copia un área de origen especificada del búfer de pantalla en un área de destino determinada.

System_CAPS_pubmethodSystem_CAPS_staticMoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor)

Copia un área de origen especificada del búfer de pantalla en un área de destino determinada.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardError()

Adquiere el flujo de error estándar.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardError(Int32)

Adquiere el flujo de error estándar, que se establece en un tamaño de búfer especificado.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardInput()

Adquiere el flujo de entrada estándar.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardInput(Int32)

Adquiere el flujo de entrada estándar, que se establece en un tamaño de búfer especificado.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardOutput()

Adquiere el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticOpenStandardOutput(Int32)

Adquiere el flujo de salida estándar, que se establece en un tamaño de búfer especificado.

System_CAPS_pubmethodSystem_CAPS_staticRead()

Lee el siguiente carácter del flujo de entrada estándar.

System_CAPS_pubmethodSystem_CAPS_staticReadKey()

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. La tecla presionada se muestra en la ventana de la consola.

System_CAPS_pubmethodSystem_CAPS_staticReadKey(Boolean)

Obtiene la siguiente tecla de carácter o de función presionada por el usuario. Opcionalmente, la tecla presionada se muestra en la ventana de la consola.

System_CAPS_pubmethodSystem_CAPS_staticReadLine()

Lee la siguiente línea de caracteres del flujo de entrada estándar.

System_CAPS_pubmethodSystem_CAPS_staticResetColor()

Establece los colores de primer plano y de fondo de la consola en sus valores predeterminados.

System_CAPS_pubmethodSystem_CAPS_staticSetBufferSize(Int32, Int32)

Establece el alto y el ancho del área del búfer de pantalla en los valores especificados.

System_CAPS_pubmethodSystem_CAPS_staticSetCursorPosition(Int32, Int32)

Establece la posición del cursor.

System_CAPS_pubmethodSystem_CAPS_staticSetError(TextWriter)

Establece la propiedad Error en el objeto TextWriter especificado.

System_CAPS_pubmethodSystem_CAPS_staticSetIn(TextReader)

Establece la propiedad In en el objeto TextReader especificado.

System_CAPS_pubmethodSystem_CAPS_staticSetOut(TextWriter)

Establece la propiedad Out en el objeto TextWriter especificado.

System_CAPS_pubmethodSystem_CAPS_staticSetWindowPosition(Int32, Int32)

Establece la posición de la ventana de la consola con respecto al búfer de pantalla.

System_CAPS_pubmethodSystem_CAPS_staticSetWindowSize(Int32, Int32)

Establece el alto y el ancho de la ventana de la consola en los valores especificados.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Boolean)

Escribe la representación de texto del valor booleano especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Char)

Escribe el valor del carácter Unicode especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Char[])

Escribe la matriz especificada de caracteres Unicode en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Char[], Int32, Int32)

Escribe la submatriz de caracteres Unicode especificada en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Decimal)

Escribe la representación de texto del valor Decimal especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Double)

Escribe la representación de texto del valor de punto flotante de precisión doble especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Int32)

Escribe la representación de texto del valor entero de 32 bits con signo especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Int64)

Escribe la representación de texto del valor entero de 64 bits con signo especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Object)

Escribe la representación de texto del objeto especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(Single)

Escribe la representación de texto del valor de punto flotante de precisión sencilla especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String)

Escribe el valor de cadena especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String, Object)

Escribe la representación de texto del objeto especificado en el flujo de salida estándar usando la información de formato indicada.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String, Object, Object)

Escribe la representación de texto de los objetos especificados en el flujo de salida estándar usando la información de formato indicada.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String, Object, Object, Object)

Escribe la representación de texto de los objetos especificados en el flujo de salida estándar usando la información de formato indicada.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String, Object, Object, Object, Object)

Escribe la representación de texto de los objetos especificados y la lista de parámetros de longitud variable en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWrite(String, Object[])

Escribe la representación de texto de la matriz de objetos especificada en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWrite(UInt32)

Escribe la representación de texto del valor entero de 32 bits sin signo especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWrite(UInt64)

Escribe la representación de texto del valor entero de 64 bits sin signo especificado en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine()

Escribe el terminador de línea actual en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Boolean)

Escribe la representación de texto del valor booleano especificado, seguida del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Char)

Escribe el carácter Unicode especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Char[])

Escribe la matriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Char[], Int32, Int32)

Escribe la submatriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Decimal)

Escribe la representación de texto del valor Decimal especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Double)

Escribe la representación de texto del valor de punto flotante de precisión doble especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Int32)

Escribe la representación de texto del valor entero de 32 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Int64)

Escribe la representación de texto del valor entero de 64 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Object)

Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(Single)

Escribe la representación de texto del valor de punto flotante de precisión sencilla especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String)

Escribe el valor de cadena especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String, Object)

Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String, Object, Object)

Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String, Object, Object, Object)

Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String, Object, Object, Object, Object)

Escribe la representación de texto de los objetos especificados y la lista de parámetros de longitud variable, seguidas del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(String, Object[])

Escribe la representación de texto de la matriz de objetos especificada, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(UInt32)

Escribe la representación de texto del valor entero de 32 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

System_CAPS_pubmethodSystem_CAPS_staticWriteLine(UInt64)

Escribe la representación de texto del valor entero de 64 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.

NombreDescripción
System_CAPS_pubeventSystem_CAPS_staticCancelKeyPress

Se produce cuando la tecla modificadora Control (Ctrl) y la tecla de consola ConsoleKey.C (C) o la tecla Interrumpir se presionan simultáneamente (Ctrl+C o Ctrl+Inter).

System_CAPS_noteNota

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#mscorlib/system/console.cs#f907d79481da6ba4. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The console is an operating system window where users interact with the operating system or with a text-based console application by entering text input through the computer keyboard, and by reading text output from the computer terminal. For example, in the Windows operating system, the console is called the Command Prompt window and accepts MS-DOS commands. The T:System.Console class provides basic support for applications that read characters from, and write characters to, the console.

For information about developing with the T:System.Console class, see the following sections:

When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the P:System.Console.In, P:System.Console.Out, and P:System.Console.Error properties.

By default, the value of the P:System.Console.In property is a T:System.IO.TextReader object that represents the keyboard, and the values of the P:System.Console.Out and P:System.Console.Error properties are T:System.IO.TextWriter objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the M:System.Console.SetIn(System.IO.TextReader), M:System.Console.SetOut(System.IO.TextWriter), or M:System.Console.SetError(System.IO.TextWriter) method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as M:System.IO.TextReader.ReadLineAsync, execute synchronously if the object represents a console stream.

System_CAPS_noteNota

Do not use the T:System.Console class to display output in unattended applications, such as server applications. Calls to methods such as Overload:System.Console.Write and Overload:System.Console.WriteLine have no effect in GUI applications.

Console class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Program your application to catch System.IO.IOException exceptions if you redirect a standard stream. You can also use the IsOutputRedirected, IsInputRedirected, and IsErrorRedirected properties to determine whether a standard stream is redirected before performing an operation that throws an System.IO.IOException exception.

It is sometimes useful to explicitly call the members of the stream objects represented by the P:System.Console.In, P:System.Console.Out, and P:System.Console.Error properties. For example, by default, the M:System.Console.ReadLine method reads input from the standard input stream. Similarly, the M:System.Console.WriteLine method writes data to the standard output stream, and the data is followed by the default line termination string, which is a carriage return and line feed ("\r\n"). However, the T:System.Console class does not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream.

You can solve this problem by setting the P:System.IO.TextWriter.NewLine property of the P:System.Console.Out or P:System.Console.Error property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences:

Console.Error.NewLine = "\r\n\r\n";

You can then explicitly call the Overload:System.IO.TextWriter.WriteLine method of the error output stream object, as in the following C# statement:

Console.Error.WriteLine();

Two closely related features of the console are the screen buffer and the console window. Text is actually read from or written to streams owned by the console, but appear to be read from or written to an area owned by the console called the screen buffer. The screen buffer is an attribute of the console, and is organized as a rectangular grid of rows and columns where each grid intersection, or character cell, can contain a character. Each character has its own foreground color, and each character cell has its own background color.

The screen buffer is viewed through a rectangular region called the console window. The console window is another attribute of the console; it is not the console itself, which is an operating system window. The console window is arranged in rows and columns, is less than or equal to the size of the screen buffer, and can be moved to view different areas of the underlying screen buffer. If the screen buffer is larger than the console window, the console automatically displays scroll bars so the console window can be repositioned over the screen buffer area.

A cursor indicates the screen buffer position where text is currently read or written. The cursor can be hidden or made visible, and its height can be changed. If the cursor is visible, the console window position is moved automatically so the cursor is always in view.

The origin for character cell coordinates in the screen buffer is the upper left corner, and the positions of the cursor and the console window are measured relative to that origin. Use zero-based indexes to specify positions; that is, specify the topmost row as row 0, and the leftmost column as column 0. The maximum value for the row and column indexes is F:System.Int16.MaxValue.

In general, the console reads input and writes output by using the current console code page, which the system locale defines by default. A code page can handle only a subset of available Unicode characters, so if you try to display characters that are not mapped by a particular code page, the console won't be able to display all characters or represent them accurately. The following example illustrates this problem. It tries to display the characters of the Cyrillic alphabet from U+0410 to U+044F to the console. If you run the example on a system that uses console code page 437, each character is replaced by a question mark (?), because Cyrillic characters do not map to the characters in code page 437.

using System;

public class Example
{
   public static void Main()
   {
      // Create a Char array for the modern Cyrillic alphabet, 
      // from U+0410 to U+044F.
      int nChars = 0x044F - 0x0410 + 1;
      char[] chars = new char[nChars];
      ushort codePoint = 0x0410;
      for (int ctr = 0; ctr < chars.Length; ctr++) {
        chars[ctr] = Convert.ToChar(codePoint);
        codePoint++;
      }   

      Console.WriteLine("Current code page: {0}\n", 
                        Console.OutputEncoding.CodePage);
      // Display the characters.
      foreach (var ch in chars) {
         Console.Write("{0}  ", ch);
         if (Console.CursorLeft >= 70) 
            Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    Current code page: 437
//    
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?

In addition to supporting code pages, the T:System.Console class supports UTF-8 encoding with the T:System.Text.UTF8Encoding class. Beginning with the .NET Framework 4.5, the T:System.Console class also supports UTF-16 encoding with the T:System.Text.UnicodeEncoding class. To display Unicode characters to the console. you set the P:System.Console.OutputEncoding property to either T:System.Text.UTF8Encoding or T:System.Text.UnicodeEncoding.

Support for Unicode characters requires the encoder to recognize a particular Unicode character, and also requires a font that has the glyphs needed to render that character. To successfully display Unicode characters to the console, the console font must be set to a non-raster or TrueType font such as Consolas or Lucida Console. The following example shows how you can programmatically change the font from a raster font to Lucida Console.

using System;
using System.Runtime.InteropServices;

public class Example
{
   [DllImport("kernel32.dll", SetLastError = true)]
   static extern IntPtr GetStdHandle(int nStdHandle);

   [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
   static extern bool GetCurrentConsoleFontEx(
          IntPtr consoleOutput, 
          bool maximumWindow,
          ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);

   [DllImport("kernel32.dll", SetLastError = true)]
   static extern bool SetCurrentConsoleFontEx(
          IntPtr consoleOutput, 
          bool maximumWindow,
          CONSOLE_FONT_INFO_EX consoleCurrentFontEx);

   private const int STD_OUTPUT_HANDLE = -11;
   private const int TMPF_TRUETYPE = 4;
   private const int LF_FACESIZE = 32;
   private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

   public static unsafe void Main()
   {
      string fontName = "Lucida Console";
      IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
      if (hnd != INVALID_HANDLE_VALUE) {
         CONSOLE_FONT_INFO_EX info = new CONSOLE_FONT_INFO_EX();
         info.cbSize = (uint) Marshal.SizeOf(info);
         bool tt = false;
         // First determine whether there's already a TrueType font.
         if (GetCurrentConsoleFontEx(hnd, false, ref info)) {
            tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
            if (tt) {
               Console.WriteLine("The console already is using a TrueType font.");
               return;
            }
            // Set console font to Lucida Console.
            CONSOLE_FONT_INFO_EX newInfo = new CONSOLE_FONT_INFO_EX();
            newInfo.cbSize = (uint) Marshal.SizeOf(newInfo);          
            newInfo.FontFamily = TMPF_TRUETYPE;
            IntPtr ptr = new IntPtr(newInfo.FaceName);
            Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
            // Get some settings from current font.
            newInfo.dwFontSize = new COORD(info.dwFontSize.X, info.dwFontSize.Y);
            newInfo.FontWeight = info.FontWeight;
            SetCurrentConsoleFontEx(hnd, false, newInfo);
         }
      }    
    }

   [StructLayout(LayoutKind.Sequential)]
   internal struct COORD
   {
      internal short X;
      internal short Y;

      internal COORD(short x, short y)
      {
         X = x;
         Y = y;
      }
   }

   [StructLayout(LayoutKind.Sequential)]
   internal unsafe struct CONSOLE_FONT_INFO_EX 
   {
      internal uint cbSize;
      internal uint nFont;
      internal COORD dwFontSize;
      internal int FontFamily;
      internal int FontWeight;
      internal fixed char FaceName[LF_FACESIZE];
   } 
}

However, TrueType fonts can display only a subset of glyphs. For example, the Lucida Console font displays only 643 of the approximately 64,000 available characters from U+0021 to U+FB02. To see which characters a particular font supports, open the Fonts applet in Control Panel, choose the Find a character option, and choose the font whose character set you'd like to examine in the Font list of the Character Map window.

Windows uses font linking to display glyphs that are not available in a particular font. For information about font linking to display additional character sets, see Globalization Step-by-Step: Fontshttp://go.microsoft.com/fwlink/?LinkId=229111. Linked fonts are defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink subkey of the registry. Each entry associated with this subkey corresponds to the name of a base font, and its value is a string array that defines the font files and the fonts that are linked to the base font. Each member of the array defines a linked font and takes the form font-file-name,font-name. The following example illustrates how you can programmatically define a linked font named SimSun found in a font file named simsun.ttc that displays Simplified Han characters.

using Microsoft.Win32;
using System;

public class Example
{
   public static void Main()
   {
      string valueName = "Lucida Console";
      string newFont = "simsun.ttc,SimSun";
      string[] fonts = null;
      RegistryValueKind kind = 0; 
      bool toAdd;

      RegistryKey key = Registry.LocalMachine.OpenSubKey( 
                 @"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink", 
                 true);
      if (key == null) {
         Console.WriteLine("Font linking is not enabled.");
      }
      else {
         // Determine if the font is a base font.
         string[] names = key.GetValueNames();
         if (Array.Exists(names, s => s.Equals(valueName, 
                                      StringComparison.OrdinalIgnoreCase))) {
            // Get the value's type.
            kind = key.GetValueKind(valueName);

            // Type should be RegistryValueKind.MultiString, but we can't be sure.
            switch (kind) {
               case RegistryValueKind.String:
                  fonts = new string[] { (string) key.GetValue(valueName) };
                  break;   
               case RegistryValueKind.MultiString:
                  fonts = (string[]) key.GetValue(valueName);
                  break;
               case RegistryValueKind.None:
                  // Do nothing.
                  fonts = new string[] { };
                  break;
            } 
            // Determine whether SimSun is a linked font.
            if (Array.FindIndex(fonts, s =>s.IndexOf("SimSun", 
                                       StringComparison.OrdinalIgnoreCase) >=0) >= 0) {
               Console.WriteLine("Font is already linked.");
               toAdd = false;
            }
            else {
               // Font is not a linked font.
               toAdd = true;
            }
         }
         else {
            // Font is not a base font.
            toAdd = true;
            fonts = new string[] { };
         }

         if (toAdd) {  
            Array.Resize(ref fonts, fonts.Length + 1);
            fonts[fonts.GetUpperBound(0)] = newFont;
            // Change REG_SZ to REG_MULTI_SZ.
            if (kind == RegistryValueKind.String)
               key.DeleteValue(valueName, false);

            key.SetValue(valueName, fonts, RegistryValueKind.MultiString);
            Console.WriteLine("SimSun added to the list of linked fonts.");
         }                     
      }

      if (key != null) key.Close();
   }
}

Unicode support for the console has the following limitations:

  • UTF-32 encoding is not supported. The only supported Unicode encodings are UTF-8 and UTF-16, which are represented by the T:System.Text.UTF8Encoding and T:System.Text.UnicodeEncoding classes, respectively.

  • Bidirectional output is not supported.

  • Display of characters outside the Basic Multilingual Plane (that is, of surrogate pairs) is not supported, even if they are defined in a linked font file.

  • Display of characters in complex scripts is not supported.

  • Combining character sequences (that is, characters that consist of a base character and one or more combining characters) are displayed as separate characters. To work around this limitation, you can normalize the string to be displayed by calling the M:System.String.Normalize method before sending output to the console. In the following example, a string that contains the combining character sequence U+0061 U+0308 is displayed to the console as two characters before the output string is normalized, and as a single character after the M:System.String.Normalize method is called.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          char[] chars = { '\u0061', '\u0308' };
    
          string combining = new String(chars);
          Console.WriteLine(combining);
    
          combining = combining.Normalize();
          Console.WriteLine(combining);
       }
    }
    // The example displays the following output:
    //       a"
    //       ä
    

    Note that normalization is a viable solution only if the Unicode standard for the character includes a pre-composed form that corresponds to a particular combining character sequence.

  • If a font provides a glyph for a code point in the private use area, that glyph will be displayed. However, because characters in the private use area are application-specific, this may not be the expected glyph.

The following example displays a range of Unicode characters to the console. The example accepts three command-line parameters: the start of the range to display, the end of the range to display, and whether to use the current console encoding (false) or UTF-16 encoding (true). It assumes that the console is using a TrueType font.

using System;
using System.IO;
using System.Globalization;
using System.Text;

public static class DisplayChars
{
   private static void Main(string[] args)
   {
      uint rangeStart = 0;
      uint rangeEnd = 0;
      bool setOutputEncodingToUnicode = true;
      // Get the current encoding so we can restore it.
      Encoding originalOutputEncoding = Console.OutputEncoding;

   	try
   	{
         switch(args.Length)
         {
            case 2:
               rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
               rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
               setOutputEncodingToUnicode = true;
               break;
            case 3:
               if (! uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
                  throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0]));

               if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
                  throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1]));

               bool.TryParse(args[2], out setOutputEncodingToUnicode);
               break;
            default:
               Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]", 
                                 Environment.GetCommandLineArgs()[0], 
                                 "startingCodePointInHex", 
                                 "endingCodePointInHex", 
                                 "<setOutputEncodingToUnicode?{true|false, default:false}>");
               return;
         }

         if (setOutputEncodingToUnicode) {
            // This won't work before .NET Framework 4.5.
            try {
               // Set encoding using endianness of this system.
               // We're interested in displaying individual Char objects, so 
               // we don't want a Unicode BOM or exceptions to be thrown on
               // invalid Char values.
               Console.OutputEncoding = new UnicodeEncoding(! BitConverter.IsLittleEndian, false); 
               Console.WriteLine("\nOutput encoding set to UTF-16");
            }
            catch (IOException) {
               Console.OutputEncoding = new UTF8Encoding();
               Console.WriteLine("Output encoding set to UTF-8");
            }
         }
         else {
            Console.WriteLine("The console encoding is {0} (code page {1})", 
                              Console.OutputEncoding.EncodingName,
                              Console.OutputEncoding.CodePage);
         }
         DisplayRange(rangeStart, rangeEnd);
      }
      catch (ArgumentException ex) {
         Console.WriteLine(ex.Message);
      }
      finally {
         // Restore console environment.
         Console.OutputEncoding = originalOutputEncoding;
      }
   }

   public static void DisplayRange(uint start, uint end)
   {
      const uint upperRange = 0x10FFFF;
      const uint surrogateStart = 0xD800;
      const uint surrogateEnd = 0xDFFF;

      if (end <= start) {
         uint t = start;
         start = end;
         end = t;
      }

      // Check whether the start or end range is outside of last plane.
      if (start > upperRange)
         throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
                                                   start, upperRange));                                   
      if (end > upperRange)
         throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
                                                   end, upperRange));

      // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
      if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd ))
         throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}", 
                                                   start, end, surrogateStart, surrogateEnd));         
      uint last = RoundUpToMultipleOf(0x10, end);
      uint first = RoundDownToMultipleOf(0x10, start);

      uint rows = (last - first) / 0x10;

      for (uint r = 0; r < rows; ++r) {
         // Display the row header.
         Console.Write("{0:x5} ", first + 0x10 * r);

         for (uint c = 0; c < 0x10; ++c) {
            uint cur = (first + 0x10 * r + c);
            if (cur  < start) {
               Console.Write(" {0} ", Convert.ToChar(0x20));
            }
            else if (end < cur) {
               Console.Write(" {0} ", Convert.ToChar(0x20));
            }
            else {
               // the cast to int is safe, since we know that val <= upperRange.
               String chars = Char.ConvertFromUtf32( (int) cur);
               // Display a space for code points that are not valid characters.
               if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) == 
                                               UnicodeCategory.OtherNotAssigned)
                  Console.Write(" {0} ", Convert.ToChar(0x20));
               // Display a space for code points in the private use area.
               else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
                                              UnicodeCategory.PrivateUse)
                 Console.Write(" {0} ", Convert.ToChar(0x20));
               // Is surrogate pair a valid character?
               // Note that the console will interpret the high and low surrogate
               // as separate (and unrecognizable) characters.
               else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) == 
                                            UnicodeCategory.OtherNotAssigned)
                  Console.Write(" {0} ", Convert.ToChar(0x20));
               else
                  Console.Write(" {0} ", chars); 
            }

            switch (c) {
               case 3: case 11:
                  Console.Write("-");
                  break;
               case 7:
                  Console.Write("--");
                  break;
            }
         }

         Console.WriteLine();
         if (0 < r && r % 0x10 == 0)
            Console.WriteLine();
      }
   }

   private static uint RoundUpToMultipleOf(uint b, uint u)
   {
      return RoundDownToMultipleOf(b, u) + b;
   }

   private static uint RoundDownToMultipleOf(uint b, uint u)
   {
      return u - (u % b);
   }
}
// If the example is run with the command line
//       DisplayChars 0400 04FF true
// the example displays the Cyrillic character set as follows:
//       Output encoding set to UTF-16
//       00400  Ѐ  Ё  Ђ  Ѓ - Є  Ѕ  І  Ї -- Ј  Љ  Њ  Ћ - Ќ  Ѝ  Ў  Џ
//       00410  А  Б  В  Г - Д  Е  Ж  З -- И  Й  К  Л - М  Н  О  П
//       00420  Р  С  Т  У - Ф  Х  Ц  Ч -- Ш  Щ  Ъ  Ы - Ь  Э  Ю  Я
//       00430  а  б  в  г - д  е  ж  з -- и  й  к  л - м  н  о  п
//       00440  р  с  т  у - ф  х  ц  ч -- ш  щ  ъ  ы - ь  э  ю  я
//       00450  ѐ  ё  ђ  ѓ - є  ѕ  і  ї -- ј  љ  њ  ћ - ќ  ѝ  ў  џ
//       00460  Ѡ  ѡ  Ѣ  ѣ - Ѥ  ѥ  Ѧ  ѧ -- Ѩ  ѩ  Ѫ  ѫ - Ѭ  ѭ  Ѯ  ѯ
//       00470  Ѱ  ѱ  Ѳ  ѳ - Ѵ  ѵ  Ѷ  ѷ -- Ѹ  ѹ  Ѻ  ѻ - Ѽ  ѽ  Ѿ  ѿ
//       00480  Ҁ  ҁ  ҂  ҃ - ҄  ҅  ҆  ҇ -- ҈  ҉  Ҋ  ҋ - Ҍ  ҍ  Ҏ  ҏ
//       00490  Ґ  ґ  Ғ  ғ - Ҕ  ҕ  Җ  җ -- Ҙ  ҙ  Қ  қ - Ҝ  ҝ  Ҟ  ҟ
//       004a0  Ҡ  ҡ  Ң  ң - Ҥ  ҥ  Ҧ  ҧ -- Ҩ  ҩ  Ҫ  ҫ - Ҭ  ҭ  Ү  ү
//       004b0  Ұ  ұ  Ҳ  ҳ - Ҵ  ҵ  Ҷ  ҷ -- Ҹ  ҹ  Һ  һ - Ҽ  ҽ  Ҿ  ҿ
//       004c0  Ӏ  Ӂ  ӂ  Ӄ - ӄ  Ӆ  ӆ  Ӈ -- ӈ  Ӊ  ӊ  Ӌ - ӌ  Ӎ  ӎ  ӏ
//       004d0  Ӑ  ӑ  Ӓ  ӓ - Ӕ  ӕ  Ӗ  ӗ -- Ә  ә  Ӛ  ӛ - Ӝ  ӝ  Ӟ  ӟ
//       004e0  Ӡ  ӡ  Ӣ  ӣ - Ӥ  ӥ  Ӧ  ӧ -- Ө  ө  Ӫ  ӫ - Ӭ  ӭ  Ӯ  ӯ
//       004f0  Ӱ  ӱ  Ӳ  ӳ - Ӵ  ӵ  Ӷ  ӷ -- Ӹ  ӹ  Ӻ  ӻ - Ӽ  ӽ  Ӿ  ӿ

The T:System.Console class contains the following methods for reading console input and writing console output:

  • The overloads of the M:System.Console.ReadKey method read an individual character.

  • The M:System.Console.ReadLine method reads an entire line of input.

  • The M:System.Console.Write(System.Boolean) method overloads convert an instance of a value type, an array of characters, or a set of objects to a formatted or unformatted string, and then write that string to the console.

  • A parallel set of M:System.Console.WriteLine method overloads output the same string as the M:System.Console.Write(System.Boolean) overloads but also add a line termination string.

The T:System.Console class also contains methods and properties to perform the following operations:

  • Get or set the size of the screen buffer. The P:System.Console.BufferHeight and P:System.Console.BufferWidth properties let you get or set the buffer height and width, respectively, and the M:System.Console.SetBufferSize(System.Int32,System.Int32) method lets you set the buffer size in a single method call.

  • Get or set the size of the console window. The P:System.Console.WindowHeight and P:System.Console.WindowWidth properties let you get or set the window height and width, respectively, and the M:System.Console.SetWindowSize(System.Int32,System.Int32) method lets you set the window size in a single method call.

  • Get or set the size of the cursor. The P:System.Console.CursorSize property specifies the height of the cursor in a character cell.

  • Get or set the position of the console window relative to the screen buffer. The P:System.Console.WindowTop and P:System.Console.WindowLeft properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the M:System.Console.SetWindowPosition(System.Int32,System.Int32) method lets you set these values in a single method call.

  • Get or set the position of the cursor by getting or setting the P:System.Console.CursorTop and P:System.Console.CursorLeft properties, or set the position of the cursor by calling the M:System.Console.SetCursorPosition(System.Int32,System.Int32) method.

  • Move or clear data in the screen buffer by calling the M:System.Console.MoveBufferArea(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32) or M:System.Console.Clear method.

  • Get or set the foreground and background colors by using the P:System.Console.ForegroundColor and P:System.Console.BackgroundColor properties, or reset the background and foreground to their default colors by calling the M:System.Console.ResetColor method.

  • Play the sound of a beep through the console speaker by calling the M:System.Console.Beep method.

In the .NET Framework on the desktop, the T:System.Console class uses the encoding returned by GetConsoleCP and GetConsoleOutputCP, which typically is a code page encoding. For example code, on systems whose culture is English (United States), code page 437 is the encoding that is used by default. However, net_core may make only a limited subset of these encodings available. Where this is the case, P:System.Text.Encoding.UTF8 is used as the default encoding for the console.

If your app depends on specific code page encodings, you can still make them available by doing the following before you call any T:System.Console methods:

  1. Add a reference to the System.Text.Encoding.CodePages.dll assembly to your project.

  2. Retrieve the T:System.Text.EncodingProvider object from the P:System.Text.CodePagesEncodingProvider.Instance property.

  3. Pass the T:System.Text.EncodingProvider object to the M:System.Text.Encoding.RegisterProvider(System.Text.EncodingProvider) method to make the additional encodings supported by the encoding provider available.

The T:System.Console class will then automatically use the default system encoding rather than UTF8, provided that you have registered the encoding provider before calling any T:System.Console output methods.

The following example demonstrates how to read data from, and write data to, the standard input and output streams. Note that these streams can be redirected by using the M:System.Console.SetIn(System.IO.TextReader) and M:System.Console.SetOut(System.IO.TextWriter) methods.

using System;

public class Example {
    public static void Main() 
    {
        Console.Write("Hello ");
        Console.WriteLine("World!");
        Console.Write("Enter your name: ");
        String name = Console.ReadLine();
        Console.Write("Good day, ");
        Console.Write(name);
        Console.WriteLine("!");
    }
}
// The example displays output similar to the following:
//       Hello World!
//       Enter your name: James
//       Good day, James!

.NET Framework
Disponible desde 1.1
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0

This type is thread safe.

Volver al principio
Mostrar: