Console 类

定义

表示控制台应用程序的标准输入流、输出流和错误流。Represents the standard input, output, and error streams for console applications. 此类不能被继承。This class cannot be inherited.

public ref class Console abstract sealed
public static class Console
type Console = class
Public Class Console
继承
Console

示例

下面的示例演示如何从标准输入和输出流中读取数据以及向其中写入数据。The following example demonstrates how to read data from, and write data to, the standard input and output streams. 请注意,这些流可以使用 SetInSetOut 方法进行重定向。Note that these streams can be redirected by using the SetIn and SetOut methods.

using namespace System;

int main()
{
   Console::Write( L"Hello " );
   Console::WriteLine( L"World!" );
   Console::Write( L"Enter your name: " );
   String^ name = Console::ReadLine();
   Console::Write( L"Good day, " );
   Console::Write( name );
   Console::WriteLine( L"!" );
}
// The example displays output similar to the following:
//       Hello World!
//       Enter your name: James
//       Good day, James!
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!
Public Class Example
    Public Shared Sub Main()
        Console.Write("Hello ")
        Console.WriteLine("World!")
        Console.Write("Enter your name: ")
        Dim name As String = Console.ReadLine()
        Console.Write("Good day, ")
        Console.Write(name)
        Console.WriteLine("!")
    End Sub
End Class 
' The example displays output similar to the following:
'        Hello World!
'        Enter your name: James
'        Good day, James!

注解

控制台是一个操作系统窗口,用户可在其中通过计算机键盘输入文本输入并读取计算机终端的文本输出,与操作系统或基于文本的控制台应用程序交互。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. 例如,在 Windows 操作系统中,控制台称为 "命令提示符" 窗口并接受 MS-DOS 命令。For example, in the Windows operating system, the console is called the Command Prompt window and accepts MS-DOS commands. Console 类为从控制台读取字符和向其写入字符的应用程序提供基本支持。The Console class provides basic support for applications that read characters from, and write characters to, the console.

有关利用 Console 类进行开发的信息,请参阅以下部分:For information about developing with the Console class, see the following sections:

控制台 i/o 流Console I/O Streams

当控制台应用程序启动时,操作系统会自动将三个 i/o 流与控制台关联:标准输入流、标准输出流和标准错误输出流。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. 这些流作为 Console.InConsole.OutConsole.Error 属性的值呈现给你的应用程序。These streams are presented to your application as the values of the Console.In, Console.Out, and Console.Error properties.

默认情况下,In 属性的值是表示键盘的 System.IO.TextReader 对象,OutError 属性的值是表示控制台窗口的 System.IO.TextWriter 对象。By default, the value of the In property is a System.IO.TextReader object that represents the keyboard, and the values of the Out and Error properties are 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. 若要重定向标准输入、标准输出或标准错误流,请分别调用 Console.SetInConsole.SetOutConsole.SetError 方法。To redirect the standard input, standard output, or standard error stream, call the Console.SetIn, Console.SetOut, or Console.SetError method, respectively. 使用这些流的 i/o 操作将同步,这意味着多个线程可以读取或写入流。I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. 这意味着,如果对象表示控制台流,通常是异步的异步方法(如 TextReader.ReadLineAsync)会同步执行。This means that methods that are ordinarily asynchronous, such as TextReader.ReadLineAsync, execute synchronously if the object represents a console stream.

备注

不要使用 Console 类在无人参与的应用程序中显示输出,如服务器应用程序。Do not use the Console class to display output in unattended applications, such as server applications. Console.WriteConsole.WriteLine 等方法的调用在 GUI 应用程序中不起作用。Calls to methods such as Console.Write and Console.WriteLine have no effect in GUI applications.

当基础流被定向到控制台时,Console 正常工作的类成员可能会引发异常(例如,在将流重定向到文件时)。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. 如果重定向标准流,请对应用程序进行编程以捕获 System.IO.IOException 异常。Program your application to catch System.IO.IOException exceptions if you redirect a standard stream. 你还可以使用 IsOutputRedirectedIsInputRedirectedIsErrorRedirected 属性来确定在执行引发 System.IO.IOException 异常的操作之前是否重定向了标准流。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.

有时,显式调用由 InOutError 属性表示的流对象的成员很有用。It is sometimes useful to explicitly call the members of the stream objects represented by the In, Out, and Error properties. 例如,默认情况下,Console.ReadLine 方法从标准输入流读取输入。For example, by default, the Console.ReadLine method reads input from the standard input stream. 同样,Console.WriteLine 方法将数据写入标准输出流,数据后跟默认的行终止字符串,这是一个回车符和换行("\r\n")。Similarly, the 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"). 但是,Console 类不提供将数据写入标准错误输出流的相应方法,也不提供更改写入到流的数据的行终止字符串的属性。However, the 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.

若要解决此问题,可以将 OutError 属性的 TextWriter.NewLine 属性设置为另一行终止字符串。You can solve this problem by setting the TextWriter.NewLine property of the Out or Error property to another line termination string. 例如,下面C#的语句将标准错误输出流的行终止字符串设置为两个回车符和换行符序列: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";

然后,你可以显式调用错误输出流对象的 WriteLine 方法,如以下C#语句所示:You can then explicitly call the WriteLine method of the error output stream object, as in the following C# statement:

Console.Error.WriteLine();

屏幕缓冲区和控制台窗口Screen Buffer and Console Window

控制台中两个密切相关的功能是屏幕缓冲区和控制台窗口。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. 使用从零开始的索引来指定位置;也就是说,将最顶部的行指定为行0,将最左侧的列指定为列0。Use zero-based indexes to specify positions; that is, specify the topmost row as row 0, and the leftmost column as column 0. Int16.MaxValue的行索引和列索引的最大值。The maximum value for the row and column indexes is Int16.MaxValue.

对控制台的 Unicode 支持Unicode Support for the Console

通常,控制台使用当前控制台代码页读取输入并写入输出,默认情况下,系统区域设置会定义此页。In general, the console reads input and writes output by using the current console code page, which the system locale defines by default. 代码页只能处理可用 Unicode 字符的一个子集,因此,如果您尝试显示不是由特定代码页映射的字符,则控制台将无法显示所有字符或准确表示它们。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. 它尝试将西里尔字母的字符从 U + 0410 到 U + 044F 显示到控制台。It tries to display the characters of the Cyrillic alphabet from U+0410 to U+044F to the console. 如果在使用控制台代码页437的系统上运行该示例,则每个字符都将替换为问号(?),因为西里尔字符不会映射到代码页437中的字符。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
//    
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
Module Example
   Public Sub Main()
      ' Create a Char array for the modern Cyrillic alphabet, 
      ' from U+0410 to U+044F.
      Dim nChars As Integer = &h44F - &h0410
      Dim chars(nChars) As Char
      Dim codePoint As UInt16 = &h0410
      For ctr As Integer = 0 To chars.Length - 1
        chars(ctr) = ChrW(codePoint)
        codePoint += CType(1, UShort)
      Next   
         
      Console.WriteLine("Current code page: {0}", 
                        Console.OutputEncoding.CodePage)
      Console.WriteLine()
      ' Display the characters.
      For Each ch In chars
         Console.Write("{0}  ", ch)
         If Console.CursorLeft >= 70 Then Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'       Current code page: 437
'       
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?

除了支持代码页以外,Console 类还支持 UTF8Encoding 类的 UTF-8 编码。In addition to supporting code pages, the Console class supports UTF-8 encoding with the UTF8Encoding class. 从 .NET Framework 4.5 开始,Console 类还支持带有 UnicodeEncoding 类的 UTF-16 编码。Beginning with the .NET Framework 4.5, the Console class also supports UTF-16 encoding with the UnicodeEncoding class. 向控制台显示 Unicode 字符。To display Unicode characters to the console. OutputEncoding 属性设置为 UTF8EncodingUnicodeEncodingyou set the OutputEncoding property to either UTF8Encoding or UnicodeEncoding.

对 Unicode 字符的支持要求编码器识别特定的 Unicode 字符,还需要具有呈现该字符所需标志符号的字体。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. 若要成功向控制台显示 Unicode 字符,控制台字体必须设置为非光栅或 TrueType 字体,如 Consolas 或宋体。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];
   } 
}
Imports System.Runtime.InteropServices

Public Module Example
   ' <DllImport("kernel32.dll", SetLastError = true)>
   Private Declare Function GetStdHandle Lib "Kernel32" (
                   nStdHandle As Integer) As IntPtr

   ' [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
   Private Declare Function GetCurrentConsoleFontEx Lib "Kernel32" ( 
                   consoleOutput As IntPtr, 
                   maximumWindow As Boolean,
                   ByRef lpConsoleCurrentFontEx As CONSOLE_FONT_INFO_EX) As Boolean
          
   ' [DllImport("kernel32.dll", SetLastError = true)]
   Private Declare Function SetCurrentConsoleFontEx Lib "Kernel32"(
                   consoleOutput As IntPtr, 
                   maximumWindow As Boolean,
                   consoleCurrentFontEx As CONSOLE_FONT_INFO_EX) As Boolean
   
   Private Const STD_OUTPUT_HANDLE As Integer = -11
   Private Const TMPF_TRUETYPE As Integer = 4
   Private Const LF_FACESIZE As Integer= 32
   Private INVALID_HANDLE_VALUE As IntPtr = New IntPtr(-1)
   
   Public Sub Main()
      Dim fontName As String = "Lucida Console"
      Dim hnd As IntPtr = GetStdHandle(STD_OUTPUT_HANDLE)
      If hnd <> INVALID_HANDLE_VALUE Then
         Dim info AS CONSOLE_FONT_INFO_EX = New CONSOLE_FONT_INFO_EX()
         info.cbSize = CUInt(Marshal.SizeOf(info))
         Dim tt As Boolean = False
         ' First determine whether there's already a TrueType font.
         If GetCurrentConsoleFontEx(hnd, False, info) Then
            tt = (info.FontFamily And TMPF_TRUETYPE) = TMPF_TRUETYPE
            If tt Then
               Console.WriteLine("The console already is using a TrueType font.")
               Return
            End If
            ' Set console font to Lucida Console.
            Dim newInfo As CONSOLE_FONT_INFO_EX = New CONSOLE_FONT_INFO_EX()
            newInfo.cbSize = CUInt(Marshal.SizeOf(newInfo))          
            newInfo.FontFamily = TMPF_TRUETYPE
            newInfo.FaceName = fontName
            ' Get some settings from current font.
            newInfo.dwFontSize = New COORD(info.dwFontSize.X, info.dwFontSize.Y)
            newInfo.FontWeight = info.FontWeight
            SetCurrentConsoleFontEx(hnd, False, newInfo)
         End If
      End If    
   End Sub
 
   <StructLayout(LayoutKind.Sequential)> Friend Structure COORD
      Friend X As Short
      Friend Y As Short
      
      Friend Sub New(x As Short, y As Short)
         Me.X = x
         Me.Y = y
      End Sub
   End Structure
 
   <StructLayout(LayoutKind.Sequential, CharSet := CharSet.Unicode)> Friend Structure CONSOLE_FONT_INFO_EX 
      Friend cbSize As UInteger
      Friend nFont As UInteger
      Friend dwFontSize As COORD
      Friend FontFamily As Integer
      Friend FontWeight As Integer
      <MarshalAs(UnmanagedType.ByValTStr, SizeConst := 32)> Friend FaceName As String
   End Structure 
End Module

但是,TrueType 字体只能显示部分字形。However, TrueType fonts can display only a subset of glyphs. 例如,$ 黑体控制台字体643只显示从 U + 0021 到 U + FB02 的大约64000个可用字符。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 使用字体链接来显示在特定字体中无法使用的标志符号。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: Fonts. 链接字体在注册表的 HKEY_LOCAL_MACHINE \SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink 子项中定义。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. 下面的示例演示如何以编程方式定义一个名为 SimSun 的链接字体,该字体文件中找到一个显示简体中文字符的 SimSun. ttc。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();
   }
}
Imports Microsoft.Win32

Module Example
   Public Sub Main()
      Dim valueName As String = "Lucida Console"
      Dim newFont As String = "simsun.ttc,SimSun"
      Dim fonts() As String = Nothing
      Dim kind As RegistryValueKind 
      Dim toAdd As Boolean
      
      Dim key As RegistryKey = Registry.LocalMachine.OpenSubKey( 
                 "Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink", 
                 True)
      If key Is Nothing Then
         Console.WriteLine("Font linking is not enabled.")
      Else
         ' Determine if the font is a base font.
         Dim names() As String = key.GetValueNames()
         If Array.Exists(names, Function(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.
            Select Case kind
               Case RegistryValueKind.String
                  fonts = { CStr(key.GetValue(valueName)) }   
               Case RegistryValueKind.MultiString
                  fonts = CType(key.GetValue(valueName), String())
               Case RegistryValueKind.None
                  ' Do nothing.
                  fonts = { }
            End Select 
            ' Determine whether SimSun is a linked font.
            If Array.FindIndex(fonts, Function(s) s.IndexOf("SimSun", 
                                      StringComparison.OrdinalIgnoreCase) >=0) >= 0 Then
               Console.WriteLine("Font is already linked.")
               toAdd = False
            Else
               ' Font is not a linked font.
               toAdd = True
            End If
         Else
            ' Font is not a base font.
            toAdd = True
            fonts = { }
         End If

         If toAdd Then  
            Array.Resize(fonts, fonts.Length + 1)
            fonts(fonts.GetUpperBound(0)) = newFont
            ' Change REG_SZ to REG_MULTI_SZ.
            If kind = RegistryValueKind.String Then
               key.DeleteValue(valueName, False)
            End If
            key.SetValue(valueName, fonts, RegistryValueKind.MultiString)
            Console.WriteLine("SimSun added to the list of linked fonts.")
         End If                     
      End If
      
      If key IsNot Nothing Then key.Close()
   End Sub
End Module

为控制台提供以下限制:Unicode support for the console has the following limitations:

  • 不支持 UTF-32 编码。UTF-32 encoding is not supported. 唯一受支持的 Unicode 编码为 UTF-8 和 UTF-16,分别由 UTF8EncodingUnicodeEncoding 类表示。The only supported Unicode encodings are UTF-8 and UTF-16, which are represented by the UTF8Encoding and 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. 若要解决此限制,可以在将输出发送到控制台之前,先调用 String.Normalize 方法,以规范化要显示的字符串。To work around this limitation, you can normalize the string to be displayed by calling the String.Normalize method before sending output to the console. 在下面的示例中,包含组合字符序列 U + 0061 U + 0308 的字符串在输出字符串被规范化之前以两个字符的形式显示在控制台上,并作为在调用 String.Normalize 方法之后的单个字符。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 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"
    //       ä
    
    Module Example
       Public Sub Main()
          Dim chars() As Char = { ChrW(&h0061), ChrW(&h0308) }
       
          Dim combining As String = New String(chars)
          Console.WriteLine(combining)
          
          combining = combining.Normalize()
          Console.WriteLine(combining)
       End Sub
    End Module
    ' The example displays the following output:
    '       a"
    '       ä
    

    请注意,仅当字符的 Unicode 标准包含对应于特定组合字符序列的预先组合形式时,规范化才可行。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.

下面的示例向控制台显示一系列 Unicode 字符。The following example displays a range of Unicode characters to the console. 该示例接受三个命令行参数:要显示的范围的开始、要显示的范围的结尾,以及是使用当前控制台编码(false)还是 UTF-16 编码(true)。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). 它假定控制台使用 TrueType 字体。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  Ӱ  ӱ  Ӳ  ӳ - Ӵ  ӵ  Ӷ  ӷ -- Ӹ  ӹ  Ӻ  ӻ - Ӽ  ӽ  Ӿ  ӿ
Imports System.IO
Imports System.Globalization
Imports System.Text

Public Module DisplayChars
   Public Sub Main(args() As String)
      Dim rangeStart As UInteger = 0
      Dim rangeEnd As UInteger = 0
      Dim setOutputEncodingToUnicode As Boolean = True
      ' Get the current encoding so we can restore it.
      Dim originalOutputEncoding As Encoding = Console.OutputEncoding

    Try
         Select Case args.Length
            Case 2
               rangeStart = UInt32.Parse(args(0), NumberStyles.HexNumber)
               rangeEnd = UInt32.Parse(args(1), NumberStyles.HexNumber)
               setOutputEncodingToUnicode = True
            Case 3
               If Not UInt32.TryParse(args(0), NumberStyles.HexNumber, Nothing, rangeStart) Then
                  Throw New ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args(0)))
               End If
               
               If Not UInt32.TryParse(args(1), NumberStyles.HexNumber, Nothing, rangeEnd) Then
                  Throw New ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args(1)))
               End If
               
               Boolean.TryParse(args(2), setOutputEncodingToUnicode)
            Case Else
               Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]", 
                                 Environment.GetCommandLineArgs()(0), 
                                 "startingCodePointInHex", 
                                 "endingCodePointInHex", 
                                 "<setOutputEncodingToUnicode?{true|false, default:false}>")
               Exit Sub
         End Select
   
         If setOutputEncodingToUnicode Then
            ' This won't work before .NET Framework 4.5.
            Try 
               ' Set encoding Imports 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(Not BitConverter.IsLittleEndian, False) 
               Console.WriteLine("{0}Output encoding set to UTF-16", vbCrLf)
            Catch e As IOException
               Console.OutputEncoding = New UTF8Encoding()
               Console.WriteLine("Output encoding set to UTF-8")
            End Try
         Else
            Console.WriteLine("The console encoding is {0} (code page {1})", 
                              Console.OutputEncoding.EncodingName,
                              Console.OutputEncoding.CodePage)
         End If
         DisplayRange(rangeStart, rangeEnd)
      Catch ex As ArgumentException
         Console.WriteLine(ex.Message)
      Finally
         ' Restore console environment.
         Console.OutputEncoding = originalOutputEncoding
      End Try
   End Sub

   Public Sub DisplayRange(rangeStart As UInteger, rangeEnd As UInteger)
      Const upperRange As UInteger = &h10FFFF
      Const surrogateStart As UInteger = &hD800
      Const surrogateEnd As UInteger = &hDFFF
       
      If rangeEnd <= rangeStart Then
         Dim t As UInteger = rangeStart
         rangeStart = rangeEnd
         rangeEnd = t
      End If

      ' Check whether the start or end range is outside of last plane.
      If rangeStart > upperRange Then
         Throw New ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
                                                   rangeStart, upperRange))                                   
      End If
      If rangeEnd > upperRange Then
         Throw New ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
                                                   rangeEnd, upperRange))
      End If
      ' Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
      If (rangeStart < surrogateStart And rangeEnd > surrogateStart) OrElse (rangeStart >= surrogateStart And rangeStart <= surrogateEnd )
         Throw New ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}", 
                                                   rangeStart, rangeEnd, surrogateStart, surrogateEnd))         
      End If
      
      Dim last As UInteger = RoundUpToMultipleOf(&h10, rangeEnd)
      Dim first As UInteger = RoundDownToMultipleOf(&h10, rangeStart)

      Dim rows As UInteger = (last - first) \ &h10

      For r As UInteger = 0 To rows - 1
         ' Display the row header.
         Console.Write("{0:x5} ", first + &h10 * r)

         For c As UInteger = 1 To &h10
            Dim cur As UInteger = first + &h10 * r + c
            If cur  < rangeStart Then
               Console.Write(" {0} ", Convert.ToChar(&h20))
            Else If rangeEnd < cur Then
               Console.Write(" {0} ", Convert.ToChar(&h20))
            Else 
               ' the cast to int is safe, since we know that val <= upperRange.
               Dim chars As String = Char.ConvertFromUtf32(CInt(cur))
               ' Display a space for code points that are not valid characters.
               If CharUnicodeInfo.GetUnicodeCategory(chars(0)) = 
                                   UnicodeCategory.OtherNotAssigned Then
                  Console.Write(" {0} ", Convert.ToChar(&h20))
               ' Display a space for code points in the private use area.
               Else If CharUnicodeInfo.GetUnicodeCategory(chars(0)) =
                                        UnicodeCategory.PrivateUse Then
                 Console.Write(" {0} ", Convert.ToChar(&h20))
               ' 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 AndAlso CharUnicodeInfo.GetUnicodeCategory(chars, 0) = 
                                            UnicodeCategory.OtherNotAssigned Then
                  Console.Write(" {0} ", Convert.ToChar(&h20))
               Else
                  Console.Write(" {0} ", chars) 
               End If   
            End If
            
            Select Case c
               Case 3, 11
                  Console.Write("-")
               Case 7
                  Console.Write("--")
            End Select
         Next

         Console.WriteLine()
         If 0 < r AndAlso r Mod &h10 = 0
            Console.WriteLine()
         End If
      Next
   End Sub

   Private Function RoundUpToMultipleOf(b As UInteger, u As UInteger) As UInteger
      Return RoundDownToMultipleOf(b, u) + b
   End Function

   Private Function RoundDownToMultipleOf(b As UInteger, u As UInteger) As UInteger
      Return u - (u Mod b)
   End Function
End Module
' 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  Ӱ  ӱ  Ӳ  ӳ - Ӵ  ӵ  Ӷ  ӷ -- Ӹ  ӹ  Ӻ  ӻ - Ӽ  ӽ  Ӿ  ӿ

常见操作Common Operations

Console 类包含以下用于读取控制台输入和写入控制台输出的方法:The Console class contains the following methods for reading console input and writing console output:

  • ReadKey 方法的重载读取单个字符。The overloads of the ReadKey method read an individual character.

  • ReadLine 方法读取整行输入。The ReadLine method reads an entire line of input.

  • Write 方法重载将值类型的实例、字符数组或一组对象转换为格式化或未格式化的字符串,然后将该字符串写入控制台。The Write 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.

  • 并行 WriteLine 方法重载与 Write 重载输出相同的字符串,但同时也添加了行终止字符串。A parallel set of WriteLine method overloads output the same string as the Write overloads but also add a line termination string.

Console 类还包含用于执行以下操作的方法和属性:The Console class also contains methods and properties to perform the following operations:

  • 获取或设置屏幕缓冲区的大小。Get or set the size of the screen buffer. 使用 BufferHeightBufferWidth 属性可以分别获取或设置缓冲区的高度和宽度,SetBufferSize 方法可让你在单个方法调用中设置缓冲区大小。The BufferHeight and BufferWidth properties let you get or set the buffer height and width, respectively, and the SetBufferSize method lets you set the buffer size in a single method call.

  • 获取或设置控制台窗口的大小。Get or set the size of the console window. 使用 "WindowHeight" 和 "WindowWidth" 属性,您可以分别获取或设置窗口的高度和宽度,使用 SetWindowSize 方法可在单个方法调用中设置窗口大小。The WindowHeight and WindowWidth properties let you get or set the window height and width, respectively, and the SetWindowSize method lets you set the window size in a single method call.

  • 获取或设置光标的大小。Get or set the size of the cursor. CursorSize 属性指定光标在字符单元格中的高度。The 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. 使用 "WindowTop" 和 "WindowLeft" 属性可获取或设置显示在控制台窗口中的屏幕缓冲区的最上面一行和最左侧的列,SetWindowPosition 方法可让你在单个方法调用中设置这些值。The WindowTop and 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 SetWindowPosition method lets you set these values in a single method call.

  • 通过获取或设置 CursorTopCursorLeft 属性获取或设置光标的位置,或通过调用 SetCursorPosition 方法设置光标的位置。Get or set the position of the cursor by getting or setting the CursorTop and CursorLeft properties, or set the position of the cursor by calling the SetCursorPosition method.

  • 通过调用 MoveBufferAreaClear 方法在屏幕缓冲区中移动或清除数据。Move or clear data in the screen buffer by calling the MoveBufferArea or Clear method.

  • 使用 "ForegroundColor" 和 "BackgroundColor" 属性获取或设置前景色和背景色,或通过调用 ResetColor 方法将背景和前景重置为其默认颜色。Get or set the foreground and background colors by using the ForegroundColor and BackgroundColor properties, or reset the background and foreground to their default colors by calling the ResetColor method.

  • 通过调用 Beep 方法,通过控制台扬声器播放提示音。Play the sound of a beep through the console speaker by calling the Beep method.

.NET Core.NET Core 说明Notes

在桌面上的 .NET Framework,Console 类使用 GetConsoleCPGetConsoleOutputCP返回的编码,这通常是一种代码页编码。In the .NET Framework on the desktop, the Console class uses the encoding returned by GetConsoleCP and GetConsoleOutputCP, which typically is a code page encoding. 例如,在区域性为英语(美国)的系统上,代码页437是默认情况下使用的编码。For example code, on systems whose culture is English (United States), code page 437 is the encoding that is used by default. .NET Core.NET Core 只能提供这些编码的有限子集。However, .NET Core.NET Core may make only a limited subset of these encodings available. 在这种情况下,Encoding.UTF8 用作控制台的默认编码。Where this is the case, Encoding.UTF8 is used as the default encoding for the console.

如果你的应用程序依赖于特定的代码页编码,你仍可以在调用任何 Console 方法之前执行以下操作,使其可用:If your app depends on specific code page encodings, you can still make them available by doing the following before you call any Console methods:

  1. 将对代码页程序集的引用添加到你的项目。Add a reference to the System.Text.Encoding.CodePages.dll assembly to your project.

  2. 检索 CodePagesEncodingProvider.Instance 属性中的 EncodingProvider 对象。Retrieve the EncodingProvider object from the CodePagesEncodingProvider.Instance property.

  3. EncodingProvider 对象传递到 Encoding.RegisterProvider 方法,以使编码提供程序支持的其他编码可用。Pass the EncodingProvider object to the Encoding.RegisterProvider method to make the additional encodings supported by the encoding provider available.

如果在调用任何 Console 输出方法之前已注册了编码提供程序,则 Console 类将自动使用默认系统编码,而不是 UTF8。The Console class will then automatically use the default system encoding rather than UTF8, provided that you have registered the encoding provider before calling any Console output methods.

属性

BackgroundColor

获取或设置控制台的背景色。Gets or sets the background color of the console.

BufferHeight

获取或设置缓冲区的高度。Gets or sets the height of the buffer area.

BufferWidth

获取或设置缓冲区的宽度。Gets or sets the width of the buffer area.

CapsLock

获取一个值,该值指示 Caps Lock 键盘切换键是打开的还是关闭的。Gets a value indicating whether the CAPS LOCK keyboard toggle is turned on or turned off.

CursorLeft

获取或设置光标在缓冲区中的列位置。Gets or sets the column position of the cursor within the buffer area.

CursorSize

获取或设置光标在字符单元格中的高度。Gets or sets the height of the cursor within a character cell.

CursorTop

获取或设置光标在缓冲区中的行位置。Gets or sets the row position of the cursor within the buffer area.

CursorVisible

获取或设置一个值,用以指示光标是否可见。Gets or sets a value indicating whether the cursor is visible.

Error

获取标准错误输出流。Gets the standard error output stream.

ForegroundColor

获取或设置控制台的前景色。Gets or sets the foreground color of the console.

In

获取标准输入流。Gets the standard input stream.

InputEncoding

获取或设置控制台用于读取输入的编码。Gets or sets the encoding the console uses to read input.

IsErrorRedirected

获取指示错误输出流是否已经从标准错误流被再定位的值。Gets a value that indicates whether the error output stream has been redirected from the standard error stream.

IsInputRedirected

获取指示输入是否已从标准输入流中重定向的值。Gets a value that indicates whether input has been redirected from the standard input stream.

IsOutputRedirected

获取指示输出是否已从标准输入流中重定向的值。Gets a value that indicates whether output has been redirected from the standard output stream.

KeyAvailable

获取一个值,该值指示按键操作在输入流中是否可用。Gets a value indicating whether a key press is available in the input stream.

LargestWindowHeight

根据当前字体和屏幕分辨率获取控制台窗口可能具有的最大行数。Gets the largest possible number of console window rows, based on the current font and screen resolution.

LargestWindowWidth

根据当前字体和屏幕分辨率获取控制台窗口可能具有的最大列数。Gets the largest possible number of console window columns, based on the current font and screen resolution.

NumberLock

获取一个值,该值指示 Num Lock 键盘切换键是打开的还是关闭的。Gets a value indicating whether the NUM LOCK keyboard toggle is turned on or turned off.

Out

获取标准输出流。Gets the standard output stream.

OutputEncoding

获取或设置控制台用于写入输出的编码。Gets or sets the encoding the console uses to write output.

Title

获取或设置要显示在控制台标题栏中的标题。Gets or sets the title to display in the console title bar.

TreatControlCAsInput

获取或设置一个值,该值指示是将修改键 Control 和控制台键 C 的组合 (Ctrl+C) 视为普通输入,还是视为由操作系统处理的中断。Gets or sets a value indicating whether the combination of the Control modifier key and C console key (Ctrl+C) is treated as ordinary input or as an interruption that is handled by the operating system.

WindowHeight

获取或设置控制台窗口区域的高度。Gets or sets the height of the console window area.

WindowLeft

获取或设置控制台窗口区域的最左边相对于屏幕缓冲区的位置。Gets or sets the leftmost position of the console window area relative to the screen buffer.

WindowTop

获取或设置控制台窗口区域的最顶部相对于屏幕缓冲区的位置。Gets or sets the top position of the console window area relative to the screen buffer.

WindowWidth

获取或设置控制台窗口的宽度。Gets or sets the width of the console window.

方法

Beep()

通过控制台扬声器播放提示音。Plays the sound of a beep through the console speaker.

Beep(Int32, Int32)

通过控制台扬声器播放具有指定频率和持续时间的提示音。Plays the sound of a beep of a specified frequency and duration through the console speaker.

Clear()

清除控制台缓冲区和相应的控制台窗口的显示信息。Clears the console buffer and corresponding console window of display information.

MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32)

将屏幕缓冲区的指定源区域复制到指定的目标区域。Copies a specified source area of the screen buffer to a specified destination area.

MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor)

将屏幕缓冲区的指定源区域复制到指定的目标区域。Copies a specified source area of the screen buffer to a specified destination area.

OpenStandardError()

获取标准错误流。Acquires the standard error stream.

OpenStandardError(Int32)

获取设置为指定缓冲区大小的标准错误流。Acquires the standard error stream, which is set to a specified buffer size.

OpenStandardInput()

获取标准输入流。Acquires the standard input stream.

OpenStandardInput(Int32)

获取设置为指定缓冲区大小的标准输入流。Acquires the standard input stream, which is set to a specified buffer size.

OpenStandardOutput()

获取标准输出流。Acquires the standard output stream.

OpenStandardOutput(Int32)

获取设置为指定缓冲区大小的标准输出流。Acquires the standard output stream, which is set to a specified buffer size.

Read()

从标准输入流读取下一个字符。Reads the next character from the standard input stream.

ReadKey()

获取用户按下的下一个字符或功能键。Obtains the next character or function key pressed by the user. 按下的键显示在控制台窗口中。The pressed key is displayed in the console window.

ReadKey(Boolean)

获取用户按下的下一个字符或功能键。Obtains the next character or function key pressed by the user. 按下的键可以选择显示在控制台窗口中。The pressed key is optionally displayed in the console window.

ReadLine()

从标准输入流读取下一行字符。Reads the next line of characters from the standard input stream.

ResetColor()

将控制台的前景色和背景色设置为默认值。Sets the foreground and background console colors to their defaults.

SetBufferSize(Int32, Int32)

将屏幕缓冲区的高度和宽度设置为指定值。Sets the height and width of the screen buffer area to the specified values.

SetCursorPosition(Int32, Int32)

设置光标位置。Sets the position of the cursor.

SetError(TextWriter)

Error 属性设置为指定的 TextWriter 对象。Sets the Error property to the specified TextWriter object.

SetIn(TextReader)

In 属性设置为指定的 TextReader 对象。Sets the In property to the specified TextReader object.

SetOut(TextWriter)

Out 属性设置为面向 TextWriter 对象。Sets the Out property to target the TextWriter object.

SetWindowPosition(Int32, Int32)

设置控制台窗口相对于屏幕缓冲区的位置。Sets the position of the console window relative to the screen buffer.

SetWindowSize(Int32, Int32)

将控制台窗口的高度和宽度设置为指定值。Sets the height and width of the console window to the specified values.

Write(Boolean)

将指定的布尔值的文本表示形式写入标准输出流。Writes the text representation of the specified Boolean value to the standard output stream.

Write(Char)

将指定的 Unicode 字符值写入标准输出流。Writes the specified Unicode character value to the standard output stream.

Write(Char[])

将指定的 Unicode 字符数组写入标准输出流。Writes the specified array of Unicode characters to the standard output stream.

Write(Char[], Int32, Int32)

将指定的 Unicode 字符子数组写入标准输出流。Writes the specified subarray of Unicode characters to the standard output stream.

Write(Decimal)

将指定的 Decimal 值的文本表示形式写入标准输出流。Writes the text representation of the specified Decimal value to the standard output stream.

Write(Double)

将指定的双精度浮点值的文本表示形式写入标准输出流。Writes the text representation of the specified double-precision floating-point value to the standard output stream.

Write(Int32)

将指定的 32 位有符号整数值的文本表示写入标准输出流。Writes the text representation of the specified 32-bit signed integer value to the standard output stream.

Write(Int64)

将指定的 64 位有符号整数值的文本表示写入标准输出流。Writes the text representation of the specified 64-bit signed integer value to the standard output stream.

Write(Object)

将指定对象的文本表示形式写入标准输出流。Writes the text representation of the specified object to the standard output stream.

Write(Single)

将指定的单精度浮点值的文本表示形式写入标准输出流。Writes the text representation of the specified single-precision floating-point value to the standard output stream.

Write(String)

将指定的字符串值写入标准输出流。Writes the specified string value to the standard output stream.

Write(String, Object)

使用指定的格式信息将指定对象的文本表示形式写入标准输出流。Writes the text representation of the specified object to the standard output stream using the specified format information.

Write(String, Object, Object)

使用指定的格式信息将指定对象的文本表示形式写入标准输出流。Writes the text representation of the specified objects to the standard output stream using the specified format information.

Write(String, Object, Object, Object)

使用指定的格式信息将指定对象的文本表示形式写入标准输出流。Writes the text representation of the specified objects to the standard output stream using the specified format information.

Write(String, Object, Object, Object, Object)

使用指定的格式信息将指定的对象和可变长度参数列表的文本表示形式写入标准输出流。Writes the text representation of the specified objects and variable-length parameter list to the standard output stream using the specified format information.

Write(String, Object[])

使用指定的格式信息将指定的对象数组的文本表示形式写入标准输出流。Writes the text representation of the specified array of objects to the standard output stream using the specified format information.

Write(UInt32)

将指定的 32 位无符号整数值的文本表示写入标准输出流。Writes the text representation of the specified 32-bit unsigned integer value to the standard output stream.

Write(UInt64)

将指定的 64 位无符号整数值的文本表示写入标准输出流。Writes the text representation of the specified 64-bit unsigned integer value to the standard output stream.

WriteLine()

将当前行终止符写入标准输出流。Writes the current line terminator to the standard output stream.

WriteLine(Boolean)

将指定布尔值的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream.

WriteLine(Char)

将指定的 Unicode 字符值(后跟当前行终止符)写入标准输出流。Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.

WriteLine(Char[])

将指定的 Unicode 字符数组(后跟当前行终止符)写入标准输出流。Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream.

WriteLine(Char[], Int32, Int32)

将指定的 Unicode 字符子数组(后跟当前行终止符)写入标准输出流。Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream.

WriteLine(Decimal)

将指定的 Decimal 值的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream.

WriteLine(Double)

将指定的双精度浮点值的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified double-precision floating-point value, followed by the current line terminator, to the standard output stream.

WriteLine(Int32)

将指定的 32 位有符号整数值的文本表示(后跟当前行的结束符)写入标准输出流。Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream.

WriteLine(Int64)

将指定的 64 位有符号整数值的文本表示(后跟当前行的结束符)写入标准输出流。Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream.

WriteLine(Object)

将指定对象的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.

WriteLine(Single)

将指定的单精度浮点值的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified single-precision floating-point value, followed by the current line terminator, to the standard output stream.

WriteLine(String)

将指定的字符串值(后跟当前行终止符)写入标准输出流。Writes the specified string value, followed by the current line terminator, to the standard output stream.

WriteLine(String, Object)

使用指定的格式信息,将指定对象(后跟当前行终止符)的文本表示形式写入标准输出流。Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object, Object)

使用指定的格式信息,将指定对象的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object, Object, Object)

使用指定的格式信息,将指定对象的文本表示形式(后跟当前行终止符)写入标准输出流。Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object, Object, Object, Object)

使用指定的格式信息,将指定的对象和可变长度参数列表(后跟当前行终止符)的文本表示形式写入标准输出流。Writes the text representation of the specified objects and variable-length parameter list, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object[])

使用指定的格式信息,将指定的对象数组(后跟当前行终止符)的文本表示形式写入标准输出流。Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(UInt32)

将指定的 32 位无符号的整数值的文本表示(后跟当前行的结束符)写入标准输出流。Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream.

WriteLine(UInt64)

将指定的 64 位无符号的整数值的文本表示(后跟当前行的结束符)写入标准输出流。Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream.

事件

CancelKeyPress

Control 修改键 (Ctrl) 和 C console 键 (C) 或 Break 键同时按住(Ctrl+C 或 Ctrl+Break)时发生。Occurs when the Control modifier key (Ctrl) and either the C console key (C) or the Break key are pressed simultaneously (Ctrl+C or Ctrl+Break).

适用于

线程安全性

此类型是线程安全的。This type is thread safe.