Console Console Console Console Class

定義

表示主控台應用程式 (Console Application) 的標準輸入、輸出和錯誤資料流。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
繼承
ConsoleConsoleConsoleConsole

範例

下列範例示範如何從標準輸入和輸出資料流程讀取資料,以及將資料寫入其中。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.In,做為、 Console.OutConsole.Error屬性的值。These streams are presented to your application as the values of the Console.In, Console.Out, and Console.Error properties.

In根據預設,屬性的值Out System.IO.TextReader是代表鍵盤的物件,而和Error屬性的值則是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.SetIn呼叫Console.SetOut、或Console.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.Write的方法並Console.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. IsOutputRedirected也可以使用、和IsInputRedirected IsErrorRedirected屬性,來判斷是否要在執行擲回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.

您可以藉由將TextWriter.NewLine OutError屬性的屬性設定為另一行終止字串,來解決這個問題。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. 如果資料指標是可見的,則會自動移動主控台視窗位置,因此游標一律為 view。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類別也支援 utf-8 編碼。 UTF8EncodingIn 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屬性設定UTF8Encoding為或UnicodeEncodingyou 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. 例如,宋體的字型只會顯示從 U + 0021 到 U + FB02 大約64000個可用字元的643。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 simsun18030.ttc 的字型檔案中,定義名為 SimSun 的連結字型,其中會顯示簡化的中文字元。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 支援有下列限制: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. 和屬性可讓您分別取得或設定緩衝區的高度和寬度,而SetBufferSize方法可讓您在單一方法呼叫中設定緩衝區大小。 BufferWidth BufferHeightThe 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. 和屬性可讓您分別取得或設定視窗的高度和寬度,而SetWindowSize方法可讓您在單一方法呼叫中設定視窗大小。 WindowWidth WindowHeightThe 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. 和屬性可讓您取得或設定顯示在SetWindowPosition主控台視窗中螢幕緩衝區的頂端列和最左邊的資料行,而方法則可讓您在單一方法呼叫中設定這些值。 WindowLeft WindowTopThe 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.

  • 藉由使用ForegroundColorBackgroundColor屬性來取得或設定前景和背景色彩,或藉由呼叫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. 從屬性取得EncodingProvider物件 CodePagesEncodingProvider.InstanceRetrieve the EncodingProvider object from the CodePagesEncodingProvider.Instance property.

  3. 將物件傳遞Encoding.RegisterProvider給方法,以提供編碼提供者所支援的其他編碼。 EncodingProviderPass the EncodingProvider object to the Encoding.RegisterProvider method to make the additional encodings supported by the encoding provider available.

如果您在呼叫任何Console輸出方法之前註冊了編碼提供者,則類別會自動使用預設系統編碼,而不是UTF8。ConsoleThe 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 BackgroundColor BackgroundColor BackgroundColor

取得或設定主控台的背景色彩。Gets or sets the background color of the console.

BufferHeight BufferHeight BufferHeight BufferHeight

取得或設定緩衝區的高度。Gets or sets the height of the buffer area.

BufferWidth BufferWidth BufferWidth BufferWidth

取得或設定緩衝區的寬度。Gets or sets the width of the buffer area.

CapsLock CapsLock CapsLock CapsLock

取得值,指出已開啟或關閉 CAPS LOCK 鍵盤切換。Gets a value indicating whether the CAPS LOCK keyboard toggle is turned on or turned off.

CursorLeft CursorLeft CursorLeft CursorLeft

取得或設定緩衝區內游標的資料行位置。Gets or sets the column position of the cursor within the buffer area.

CursorSize CursorSize CursorSize CursorSize

取得或設定字元儲存格內游標的高度。Gets or sets the height of the cursor within a character cell.

CursorTop CursorTop CursorTop CursorTop

取得或設定緩衝區內游標的資料列位置。Gets or sets the row position of the cursor within the buffer area.

CursorVisible CursorVisible CursorVisible CursorVisible

取得或設定值,指出是否能看見游標。Gets or sets a value indicating whether the cursor is visible.

Error Error Error Error

取得標準錯誤輸出資料流。Gets the standard error output stream.

ForegroundColor ForegroundColor ForegroundColor ForegroundColor

取得或設定主控台的前景色彩。Gets or sets the foreground color of the console.

In In In In

取得標準輸入資料流。Gets the standard input stream.

InputEncoding InputEncoding InputEncoding InputEncoding

取得或設定主控台用來讀取輸入的編碼方式。Gets or sets the encoding the console uses to read input.

IsErrorRedirected IsErrorRedirected IsErrorRedirected IsErrorRedirected

取得值,指出是否已從標準錯誤資料流重新導向錯誤輸出資料流。Gets a value that indicates whether the error output stream has been redirected from the standard error stream.

IsInputRedirected IsInputRedirected IsInputRedirected IsInputRedirected

取得值,指出是否已從標準輸入資料流重新導向輸入。Gets a value that indicates whether input has been redirected from the standard input stream.

IsOutputRedirected IsOutputRedirected IsOutputRedirected IsOutputRedirected

取得值,指出是否已從標準輸出資料流重新導向輸出。Gets a value that indicates whether output has been redirected from the standard output stream.

KeyAvailable KeyAvailable KeyAvailable KeyAvailable

取得值,指出是否可以在輸入資料流中使用按鍵按壓。Gets a value indicating whether a key press is available in the input stream.

LargestWindowHeight LargestWindowHeight LargestWindowHeight LargestWindowHeight

根據目前的字型和螢幕解析度,取得主控台視窗資料列數的最大可能值。Gets the largest possible number of console window rows, based on the current font and screen resolution.

LargestWindowWidth LargestWindowWidth LargestWindowWidth LargestWindowWidth

根據目前的字型和螢幕解析度,取得主控台視窗資料行數的最大可能值。Gets the largest possible number of console window columns, based on the current font and screen resolution.

NumberLock NumberLock NumberLock NumberLock

取得值,指出已開啟或關閉 NUM LOCK 鍵盤切換。Gets a value indicating whether the NUM LOCK keyboard toggle is turned on or turned off.

Out Out Out Out

取得標準輸出資料流。Gets the standard output stream.

OutputEncoding OutputEncoding OutputEncoding OutputEncoding

取得或設定主控台用來寫入輸出的編碼方式。Gets or sets the encoding the console uses to write output.

Title Title Title Title

取得或設定要顯示於主控台標題列中的標題。Gets or sets the title to display in the console title bar.

TreatControlCAsInput TreatControlCAsInput TreatControlCAsInput 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 WindowHeight WindowHeight WindowHeight

取得或設定主控台視窗區域的高度。Gets or sets the height of the console window area.

WindowLeft WindowLeft WindowLeft WindowLeft

取得或設定相對於螢幕緩衝區的主控台視窗區域最左邊的位置。Gets or sets the leftmost position of the console window area relative to the screen buffer.

WindowTop WindowTop WindowTop WindowTop

取得或設定相對於螢幕緩衝區的主控台視窗區域上方的位置。Gets or sets the top position of the console window area relative to the screen buffer.

WindowWidth WindowWidth WindowWidth WindowWidth

取得或設定主控台視窗的寬度。Gets or sets the width of the console window.

方法

Beep() Beep() Beep() Beep()

透過主控台喇叭播放嗶聲。Plays the sound of a beep through the console speaker.

Beep(Int32, Int32) Beep(Int32, Int32) Beep(Int32, Int32) Beep(Int32, Int32)

以指定之頻率和持續期間透過主控台喇叭播放嗶聲。Plays the sound of a beep of a specified frequency and duration through the console speaker.

Clear() Clear() Clear() Clear()

清除主控台緩衝區及包含顯示資訊的對應主控台視窗。Clears the console buffer and corresponding console window of display information.

MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) 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) MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) 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() OpenStandardError() OpenStandardError() OpenStandardError()

擷取標準錯誤資料流。Acquires the standard error stream.

OpenStandardError(Int32) OpenStandardError(Int32) OpenStandardError(Int32) OpenStandardError(Int32)

擷取標準錯誤資料流,設定為指定的緩衝區大小。Acquires the standard error stream, which is set to a specified buffer size.

OpenStandardInput() OpenStandardInput() OpenStandardInput() OpenStandardInput()

擷取標準輸入資料流。Acquires the standard input stream.

OpenStandardInput(Int32) OpenStandardInput(Int32) OpenStandardInput(Int32) OpenStandardInput(Int32)

擷取標準輸入資料流,設定為指定的緩衝區大小。Acquires the standard input stream, which is set to a specified buffer size.

OpenStandardOutput() OpenStandardOutput() OpenStandardOutput() OpenStandardOutput()

擷取標準輸出資料流。Acquires the standard output stream.

OpenStandardOutput(Int32) OpenStandardOutput(Int32) OpenStandardOutput(Int32) OpenStandardOutput(Int32)

擷取標準輸出資料流,設定為指定的緩衝區大小。Acquires the standard output stream, which is set to a specified buffer size.

Read() Read() Read() Read()

從標準輸入資料流讀取下一個字元。Reads the next character from the standard input stream.

ReadKey() ReadKey() ReadKey() ReadKey()

取得使用者按下的下一個字元或功能鍵。Obtains the next character or function key pressed by the user. 按下的按鍵會顯示在主控台視窗中。The pressed key is displayed in the console window.

ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean) ReadKey(Boolean)

取得使用者按下的下一個字元或功能鍵。Obtains the next character or function key pressed by the user. 按下的按鍵會選擇性地顯示在主控台視窗中。The pressed key is optionally displayed in the console window.

ReadLine() ReadLine() ReadLine() ReadLine()

從標準輸入資料流讀取下一行字元。Reads the next line of characters from the standard input stream.

ResetColor() ResetColor() ResetColor() ResetColor()

將前景和背景的主控台色彩設定為預設值。Sets the foreground and background console colors to their defaults.

SetBufferSize(Int32, Int32) SetBufferSize(Int32, Int32) SetBufferSize(Int32, Int32) SetBufferSize(Int32, Int32)

將螢幕緩衝區的高度和寬度設定為指定的值。Sets the height and width of the screen buffer area to the specified values.

SetCursorPosition(Int32, Int32) SetCursorPosition(Int32, Int32) SetCursorPosition(Int32, Int32) SetCursorPosition(Int32, Int32)

設定游標的位置。Sets the position of the cursor.

SetError(TextWriter) SetError(TextWriter) SetError(TextWriter) SetError(TextWriter)

Error 屬性設定為指定的 TextWriter 物件。Sets the Error property to the specified TextWriter object.

SetIn(TextReader) SetIn(TextReader) SetIn(TextReader) SetIn(TextReader)

In 屬性設定為指定的 TextReader 物件。Sets the In property to the specified TextReader object.

SetOut(TextWriter) SetOut(TextWriter) SetOut(TextWriter) SetOut(TextWriter)

設定 Out 屬性,以 TextWriter 物件為目標。Sets the Out property to target the TextWriter object.

SetWindowPosition(Int32, Int32) SetWindowPosition(Int32, Int32) SetWindowPosition(Int32, Int32) SetWindowPosition(Int32, Int32)

將主控台視窗的位置設定為與螢幕緩衝區相對的位置。Sets the position of the console window relative to the screen buffer.

SetWindowSize(Int32, Int32) SetWindowSize(Int32, Int32) SetWindowSize(Int32, Int32) SetWindowSize(Int32, Int32)

將主控台視窗的高度和寬度設定為指定的值。Sets the height and width of the console window to the specified values.

Write(String, Object, Object, Object, Object) Write(String, Object, Object, Object, Object) Write(String, Object, Object, Object, Object) 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, Object, Object) Write(String, Object, Object, Object) Write(String, Object, Object, Object) 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) Write(String, Object, Object) Write(String, Object, Object) 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[]) Write(String, Object[]) Write(String, Object[]) Write(String, Object[])

使用指定的格式資訊,將指定之物件陣列的文字表示寫入標準輸出資料流。Writes the text representation of the specified array of objects to the standard output stream using the specified format information.

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

使用指定的格式資訊,將指定之物件的文字表示寫入標準輸出資料流。Writes the text representation of the specified object to the standard output stream using the specified format information.

Write(UInt64) Write(UInt64) Write(UInt64) Write(UInt64)

將指定 64 位元不帶正負號整數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified 64-bit unsigned integer value to the standard output stream.

Write(UInt32) Write(UInt32) Write(UInt32) Write(UInt32)

將指定 32 位元不帶正負號整數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified 32-bit unsigned integer value to the standard output stream.

Write(String) Write(String) Write(String) Write(String)

將指定的字串值寫入標準輸出資料流。Writes the specified string value to the standard output stream.

Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32)

將指定的 Unicode 字元子陣列寫入標準輸出資料流。Writes the specified subarray of Unicode characters to the standard output stream.

Write(Object) Write(Object) Write(Object) Write(Object)

將指定物件的文字表示寫入標準輸出資料流。Writes the text representation of the specified object to the standard output stream.

Write(Single) Write(Single) Write(Single) Write(Single)

將指定的單精確度浮點數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified single-precision floating-point value to the standard output stream.

Write(Char) Write(Char) Write(Char) Write(Char)

將指定的 Unicode 字元值寫入標準輸出資料流。Writes the specified Unicode character value to the standard output stream.

Write(Char[]) Write(Char[]) Write(Char[]) Write(Char[])

將指定的 Unicode 字元陣列寫入標準輸出資料流。Writes the specified array of Unicode characters to the standard output stream.

Write(Boolean) Write(Boolean) Write(Boolean) Write(Boolean)

將指定布林值 (Boolean) 的文字表示寫入標準輸出資料流。Writes the text representation of the specified Boolean value to the standard output stream.

Write(Double) Write(Double) Write(Double) Write(Double)

將指定的雙精確度浮點數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified double-precision floating-point value to the standard output stream.

Write(Int32) Write(Int32) Write(Int32) Write(Int32)

將指定 32 位元帶正負號整數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified 32-bit signed integer value to the standard output stream.

Write(Int64) Write(Int64) Write(Int64) Write(Int64)

將指定 64 位元帶正負號整數值的文字表示寫入標準輸出資料流。Writes the text representation of the specified 64-bit signed integer value to the standard output stream.

Write(Decimal) Write(Decimal) Write(Decimal) Write(Decimal)

將指定 Decimal 值的表示文字寫入標準輸出資料流。Writes the text representation of the specified Decimal value to the standard output stream.

WriteLine(String, Object, Object) WriteLine(String, Object, Object) WriteLine(String, Object, Object) 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) WriteLine(String) WriteLine(String) WriteLine(String)

將指定的字串值 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the specified string value, followed by the current line terminator, to the standard output stream.

WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32)

將指定的 Unicode 字元子陣列 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream.

WriteLine(String, Object[]) WriteLine(String, Object[]) WriteLine(String, Object[]) 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(String, Object) WriteLine(String, Object) WriteLine(String, Object) 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(UInt64) WriteLine(UInt64) WriteLine(UInt64) 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.

WriteLine(UInt32) WriteLine(UInt32) WriteLine(UInt32) 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(Single) WriteLine(Single) WriteLine(Single) 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(Decimal) WriteLine(Decimal) WriteLine(Decimal) WriteLine(Decimal)

將指定的 Decimal 值的文字表示 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream.

WriteLine(Int64) WriteLine(Int64) WriteLine(Int64) 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(Int32) WriteLine(Int32) WriteLine(Int32) 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(Double) WriteLine(Double) WriteLine(Double) 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(Char[]) WriteLine(Char[]) WriteLine(Char[]) WriteLine(Char[])

將指定的 Unicode 字元陣列 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream.

WriteLine(Char) WriteLine(Char) WriteLine(Char) WriteLine(Char)

將指定的 Unicode 字元 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.

WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean)

將指定布林值的文字表示 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream.

WriteLine() WriteLine() WriteLine() WriteLine()

將目前的行結束字元寫入標準輸出資料流。Writes the current line terminator to the standard output stream.

WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) 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(Object) WriteLine(Object) WriteLine(Object) WriteLine(Object)

將指定物件的文字表示 (後面接著目前的行結束字元) 寫入標準輸出資料流。Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.

WriteLine(String, Object, Object, Object, Object) WriteLine(String, Object, Object, Object, Object) WriteLine(String, Object, Object, Object, Object) 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.

事件

CancelKeyPress CancelKeyPress CancelKeyPress CancelKeyPress

發生於同時按下 Control 輔助按鍵 (Ctrl) 和 C 主控台按鍵 (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.