Console クラス

定義

コンソール アプリケーションの標準入力ストリーム、標準出力ストリーム、および標準エラー ストリームを表します。 このクラスは継承できません。

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

次の例では、標準の入力ストリームと出力ストリームからデータを読み取り、書き込む方法を示します。 これらのストリームは、 メソッドと SetOut メソッドを使用してリダイレクトできることにSetIn注意してください。

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!
module Example

open System

[<EntryPoint>]
let main argv =
    Console.Write("Hello ")
    Console.WriteLine("World!")
    Console.Write("Enter your name: ")
    let name = Console.ReadLine()
    Console.Write("Good day, ")
    Console.Write(name)
    Console.WriteLine("!")
    0
    
// The example displays output similar to the following:
//       Hello World!
//       Enter your name: James
//       Good day, James!

注釈

コンソールはオペレーティング システム ウィンドウであり、ユーザーは、コンピューター キーボードを介してテキスト入力を入力し、コンピューターターミナルからテキスト出力を読み取ることによって、オペレーティング システムまたはテキストベースのコンソール アプリケーションと対話します。 たとえば、Windows オペレーティング システムでは、コンソールはコマンド プロンプト ウィンドウと呼ばれ、MS-DOS コマンドを受け入れます。 クラスは Console 、コンソールから文字を読み取り、文字を書き込むアプリケーションの基本的なサポートを提供します。

クラスを使用した開発の Console 詳細については、次のセクションを参照してください。

コンソール I/O ストリーム

コンソール アプリケーションが起動すると、オペレーティング システムは、標準入力ストリーム、標準出力ストリーム、標準エラー出力ストリームの 3 つの I/O ストリームをコンソールに自動的に関連付けます。 アプリケーションは、標準入力ストリームからユーザー入力を読み取ることができます。標準出力ストリームに通常のデータを書き込みます。エラー データを標準エラー出力ストリームに書き込みます。 これらのストリームは、、、および プロパティの値としてアプリケーションにConsole.InConsole.OutConsole.Error表示されます。

既定では、 プロパティのIn値はキーボードをSystem.IO.TextReader表す オブジェクトであり、 プロパティと Error プロパティのOut値はSystem.IO.TextWriterコンソール ウィンドウを表すオブジェクトです。 ただし、これらのプロパティは、コンソール ウィンドウまたはキーボードを表さないストリームに設定できます。たとえば、これらのプロパティをファイルを表すストリームに設定できます。 標準入力、標準出力、または標準エラー ストリームをリダイレクトするには、、、または Console.SetError メソッドをそれぞれ呼び出Console.SetInConsole.SetOutします。 これらのストリームを使用する I/O 操作は同期されます。つまり、複数のスレッドがストリームの読み取りまたは書き込みを行うことができます。 これは、オブジェクトがコンソール ストリームを表す場合、通常は 非同期の メソッド (など TextReader.ReadLineAsync) が同期的に実行されることを意味します。

Note

クラスを Console 使用して、サーバー アプリケーションなどの無人アプリケーションで出力を表示しないでください。 や などの Console.Write メソッドの呼び出し Console.WriteLine は、GUI アプリケーションには影響しません。

Console 基になるストリームがコンソールに転送されるときに正常に動作するクラス メンバーは、ストリームがファイルにリダイレクトされた場合などに例外をスローする可能性があります。 標準ストリームをリダイレクトする場合は、例外をキャッチ System.IO.IOException するようにアプリケーションをプログラミングします。 、、および IsErrorRedirected プロパティをIsOutputRedirectedIsInputRedirected使用して、例外をスローSystem.IO.IOExceptionする操作を実行する前に標準ストリームがリダイレクトされるかどうかを判断することもできます。

、、および Error の各プロパティでInOut表されるストリーム オブジェクトのメンバーを明示的に呼び出すと便利な場合があります。 たとえば、既定では、 メソッドは Console.ReadLine 標準入力ストリームから入力を読み取ります。 同様に、 メソッドは Console.WriteLine 標準の出力ストリームにデータを書き込み、その後に既定の行終端文字列が続きます。これは にあります Environment.NewLine。 ただし、 クラスには、 Console 標準エラー出力ストリームにデータを書き込む対応するメソッドや、そのストリームに書き込まれるデータの行終了文字列を変更する プロパティは用意されていません。

この問題を解決するには、 プロパティまたは Error プロパティの プロパティをTextWriter.NewLineOut別の行終端文字列に設定します。 たとえば、次の C# ステートメントは、標準エラー出力ストリームの行終了文字列を 2 つの復帰シーケンスと改行シーケンスに設定します。

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

その後、次の C# ステートメントのように、エラー出力ストリーム オブジェクトの メソッドを明示的に呼び出 WriteLine すことができます。

Console.Error.WriteLine();

画面バッファーとコンソール ウィンドウ

コンソールの 2 つの密接に関連する機能は、画面バッファーとコンソール ウィンドウです。 テキストは実際にはコンソールが所有するストリームから読み取られたり、ストリームに書き込まれたりしますが、画面バッファーと呼ばれるコンソールが所有する領域から読み取られたり、書き込まれたりしているように見えます。 画面バッファーはコンソールの属性であり、行と列の四角形のグリッドとして編成され、各グリッドの交差部分または文字セルに文字を含めることができます。 各文字には前景色があり、各文字セルには独自の背景色があります。

画面バッファーは、コンソール ウィンドウと呼ばれる四角形の領域を介して表示されます。 コンソール ウィンドウは、コンソールのもう 1 つの属性です。オペレーティング システム ウィンドウであるコンソール自体ではありません。 コンソール ウィンドウは行と列に配置され、画面バッファーのサイズ以下で、基になる画面バッファーのさまざまな領域を表示するために移動できます。 画面バッファーがコンソール ウィンドウよりも大きい場合、コンソールは自動的にスクロール バーを表示し、コンソール ウィンドウを画面バッファー領域の上に再配置できるようにします。

カーソルは、テキストが現在読み取りまたは書き込まれている画面バッファー位置を示します。 カーソルは非表示にしたり、表示したりすることができ、その高さは変更できます。 カーソルが表示されている場合、コンソール ウィンドウの位置は自動的に移動されるため、カーソルは常に表示されます。

画面バッファー内の文字セル座標の原点は左上隅であり、カーソルとコンソール ウィンドウの位置は、その原点を基準にして測定されます。 位置を指定するには、0 から始まるインデックスを使用します。つまり、一番上の行を行 0、左端の列を列 0 として指定します。 行インデックスと列インデックスの最大値は です Int16.MaxValue

コンソールの Unicode サポート

一般に、コンソールは現在のコンソール コード ページを使用して入力を読み取り、出力を書き込みます。これは、システム ロケールによって既定で定義されます。 コード ページでは、使用可能な Unicode 文字のサブセットのみを処理できるため、特定のコード ページでマップされていない文字を表示しようとすると、コンソールですべての文字を表示したり、正確に表したりすることはできません。 この問題を説明する例を次に示します。 U+0410 から U+044F までのキリル文字の文字をコンソールに表示しようとします。 コンソール コード ページ 437 を使用するシステムでこの例を実行すると、キリル文字はコード ページ 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] = (char)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
'       
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
'       ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
open System

// Create a char List for the modern Cyrillic alphabet,
// from U+0410 to U+044F.
let chars =
    [ for codePoint in 0x0410 .. 0x044F do
        Convert.ToChar codePoint ]

printfn "Current code page: %i\n" Console.OutputEncoding.CodePage
// Display the characters.
for ch in chars do
    printf "%c  " ch
    if Console.CursorLeft >= 70 then Console.WriteLine()

// The example displays the following output:
//    Current code page: 437
//
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?
//    ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?

クラスは、コード ページの Console サポートに加えて、 クラスを使用した UTF-8 エンコードも UTF8Encoding サポートしています。 .NET Framework 4.5 以降では、 クラスで Console UTF-16 エンコードUnicodeEncodingもサポートされています。 コンソールに Unicode 文字を表示するには。 プロパティを または UnicodeEncodingUTF8Encoding設定しますOutputEncoding

Unicode 文字をサポートするには、エンコーダーが特定の Unicode 文字を認識する必要があります。また、その文字をレンダリングするために必要なグリフを含むフォントも必要です。 Unicode 文字をコンソールに正常に表示するには、コンソール フォントを、Consolas や Lucida Console などのラスター以外のフォントまたは TrueType フォントに設定する必要があります。 次の例は、プログラムによってフォントをラスター フォントから 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
module Example

open System
open System.Runtime.InteropServices

[<Literal>]
let STD_OUTPUT_HANDLE = -11

[<Literal>]
let TMPF_TRUETYPE = 4

[<Literal>]
let LF_FACESIZE = 32

let INVALID_HANDLE_VALUE = IntPtr(-1)


[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type COORD =
    val mutable X: int16
    val mutable Y: int16

    internal new(x: int16, y: int16) =
        { X = x
          Y = y }

[<Struct>]
[<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)>]
type CONSOLE_FONT_INFO_EX =
    val mutable cbSize: uint32
    val mutable nFont: uint32
    val mutable dwFontSize: COORD
    val mutable FontFamily: int
    val mutable FontWeight: int
    [<MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)>]
    val mutable FaceName: string

[<DllImport("kernel32.dll", SetLastError = true)>]
extern IntPtr GetStdHandle(int nStdHandle)

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

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

[<EntryPoint>]
let main argv =
    let fontName = "Lucida Console"
    let hnd = GetStdHandle(STD_OUTPUT_HANDLE)
    if hnd <> INVALID_HANDLE_VALUE then
        let mutable info = CONSOLE_FONT_INFO_EX()
        info.cbSize <- uint32 (Marshal.SizeOf(info))
        // First determine whether there's already a TrueType font.
        if (GetCurrentConsoleFontEx(hnd, false, info)) then
            if (((info.FontFamily) &&& TMPF_TRUETYPE) = TMPF_TRUETYPE) then
                Console.WriteLine("The console already is using a TrueType font.")
            else
                // Set console font to Lucida Console.
                let mutable newInfo = CONSOLE_FONT_INFO_EX()
                newInfo.cbSize <- uint32 (Marshal.SizeOf(newInfo))
                newInfo.FontFamily <- TMPF_TRUETYPE
                newInfo.FaceName <- fontName
                // Get some settings from current font.
                newInfo.dwFontSize <- COORD(info.dwFontSize.X, info.dwFontSize.Y)
                newInfo.FontWeight <- info.FontWeight
                SetCurrentConsoleFontEx(hnd, false, newInfo) |> ignore
                Console.WriteLine("The console is now using a TrueType font.")

    // Return zero for success
    0

ただし、TrueType フォントではグリフのサブセットのみを表示できます。 たとえば、Lucida コンソール フォントには、U+0021 から U+FB02 までの使用可能な約 64,000 文字のうち 643 文字のみが表示されます。 特定のフォントでサポートされている文字を確認するには、コントロール パネルで [フォント] アプレットを開き、[文字の検索] オプションを選択し、[文字マップ] ウィンドウの [フォント] ボックスの一覧で、文字セットを調べるフォントを選択します。

Windows では、フォント リンクを使用して、特定のフォントで使用できないグリフを表示します。 追加の文字セットを表示するためのフォント リンクの詳細については、「 グローバリゼーションのステップ バイ ステップ: フォント」を参照してください。 リンクされたフォントは、レジストリの HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink サブキーで定義されます。 このサブキーに関連付けられている各エントリは、基本フォントの名前に対応し、その値は、フォント ファイルと基本フォントにリンクされているフォントを定義する文字列配列です。 配列の各メンバーは、リンクされたフォントを定義し、font-file-name,font-name という形式になります。 次の例は、簡体字漢字を表示する simsun.ttc という名前のフォント ファイルにある SimSun という名前のリンクされたフォントをプログラムで定義する方法を示しています。

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
open System
open Microsoft.Win32

let valueName = "Lucida Console"
let newFont = "simsun.ttc,SimSun"

let key =
    Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink", true)
if isNull key then
    printfn "Font linking is not enabled."
else
    // Determine if the font is a base font.
    let names = key.GetValueNames()

    let (fonts, kind, toAdd) =
        if names |> Array.exists (fun s -> s.Equals(valueName, StringComparison.OrdinalIgnoreCase)) then
            // Get the value's type.
            let kind = key.GetValueKind(valueName)

            // Type should be RegistryValueKind.MultiString, but we can't be sure.
            let fonts =
                match kind with
                | RegistryValueKind.String -> [| key.GetValue(valueName) :?> string |]
                | RegistryValueKind.MultiString -> (key.GetValue(valueName) :?> string array)
                | _ -> [||]

            // Determine whether SimSun is a linked font.
            let toAdd =
                not (fonts |> Array.exists (fun s -> s.IndexOf("SimSun", StringComparison.OrdinalIgnoreCase) >= 0))

            (fonts, kind, toAdd)
        else
            // Font is not a base font.
            ([||], RegistryValueKind.Unknown, true)

    if toAdd then
        // Font is not a linked font.
        let newFonts = Array.append fonts [| newFont |]

        // Change REG_SZ to REG_MULTI_SZ.
        if kind = RegistryValueKind.String then key.DeleteValue(valueName, false)

        key.SetValue(valueName, newFonts, RegistryValueKind.MultiString)
        printfn "SimSun added to the list of linked fonts."
    else
        printfn "Font is already linked."


if not (isNull key) then key.Close()

コンソールの Unicode サポートには、次の制限があります。

  • UTF-32 エンコードはサポートされていません。 サポートされている Unicode エンコードは UTF-8 と UTF-16 のみです。これは、 クラスと UnicodeEncoding クラスでUTF8Encodingそれぞれ表されます。

  • 双方向出力はサポートされていません。

  • 基本多言語プレーンの外部 (サロゲート ペア) の文字の表示は、リンクされたフォント ファイルで定義されている場合でもサポートされません。

  • 複雑なスクリプトでの文字の表示はサポートされていません。

  • 文字シーケンスの組み合わせ (つまり、基本文字と 1 つ以上の結合文字で構成される文字) は、個別の文字として表示されます。 この制限を回避するには、コンソールに出力を送信する前に メソッドを String.Normalize 呼び出して、表示される文字列を正規化します。 次の例では、結合文字シーケンス U+0061 U+0308 を含む文字列が、出力文字列が正規化される前に 2 文字、メソッドが呼び出された後 String.Normalize の 1 文字としてコンソールに表示されます。

    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"
    '       ä
    
    open System
    
    let chars = [| '\u0061'; '\u0308' |]
    
    let combining = String chars
    Console.WriteLine combining
    
    let combining2 = combining.Normalize()
    Console.WriteLine combining2
    
    
    // The example displays the following output:
    //       a"
    //       ä
    

    正規化は、文字の Unicode 標準に、特定の組み合わせ文字シーケンスに対応する事前構成済みの形式が含まれている場合にのみ実行可能な解決策であることに注意してください。

  • フォントがプライベート使用領域のコード ポイントのグリフを提供する場合、そのグリフが表示されます。 ただし、プライベート使用領域の文字はアプリケーション固有であるため、これは想定されるグリフではない可能性があります。

次の例では、コンソールに Unicode 文字の範囲を表示します。 この例では、表示する範囲の開始、表示する範囲の末尾、および現在のコンソール エンコード () と UTF-16 エンコードtrue () のどちらを使用するかというfalse 3 つのコマンド ライン パラメーターを受け入れます。 コンソールで TrueType フォントが使用されていることを前提としています。

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($" {(char)(0x20)} ");
            }
            else if (end < cur) {
               Console.Write($" {(char)(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($" {(char)(0x20)} ");
               // Display a space for code points in the private use area.
               else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
                                              UnicodeCategory.PrivateUse)
                 Console.Write($" {(char)(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($" {(char)(0x20)} ");
               else
                  Console.Write($" {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  Ӱ  ӱ  Ӳ  ӳ - Ӵ  ӵ  Ӷ  ӷ -- Ӹ  ӹ  Ӻ  ӻ - Ӽ  ӽ  Ӿ  ӿ
module DisplayChars

open System
open System.IO
open System.Globalization
open System.Text

type uint = uint32

let inline roundDownToMultipleOf b u = u - (u % b)

let inline roundUpToMultipleOf b u = roundDownToMultipleOf b u |> (+) b

let displayRange (start: uint) (``end``: uint) =

    let upperRange = 0x10FFFFu
    let surrogateStart = 0xD800u
    let surrogateEnd = 0xDFFFu

    let start, ``end`` =
        if ``end`` <= start then ``end``, start
        else start, ``end``

    // Check whether the start or end range is outside of last plane.
    if start > upperRange then
        invalidArg "start"
            (String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})", start, upperRange))
    if ``end`` > upperRange then
        invalidArg "end"
            (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) then
        raise
            (ArgumentException
                (String.Format
                    ("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}", start, ``end``,
                     surrogateStart, surrogateEnd)))
    let last = roundUpToMultipleOf 0x10u ``end``
    let first = roundDownToMultipleOf 0x10u start

    let rows = (last - first) / 0x10u

    for r in 0u .. (rows - 1u) do
        // Display the row header.
        printf "%05x " (first + 0x10u * r)

        for c in 0u .. (0x10u - 1u) do
            let cur = (first + 0x10u * r + c)
            if cur < start || ``end`` < cur then
                printf " %c " (Convert.ToChar 0x20)
            else
                // the cast to int is safe, since we know that val <= upperRange.
                let chars = Char.ConvertFromUtf32(int cur)
                // Display a space for code points that are not valid characters.
                if CharUnicodeInfo.GetUnicodeCategory(chars[0]) = UnicodeCategory.OtherNotAssigned then
                    printf " %c " (Convert.ToChar 0x20)
                else
                    // Display a space for code points in the private use area.
                    if CharUnicodeInfo.GetUnicodeCategory(chars[0]) = UnicodeCategory.PrivateUse then
                        printf " %c " (Convert.ToChar 0x20)
                    else if chars.Length > 1
                            && CharUnicodeInfo.GetUnicodeCategory(chars, 0) = UnicodeCategory.OtherNotAssigned then
                        printf " %c " (Convert.ToChar 0x20)
                    else printf " %s " chars

            match c with
            | 3u
            | 11u -> printf "-"
            | 7u -> printf "--"
            | _ -> ()

        Console.WriteLine()
        if (0u < r && r % 0x10u = 0u) then Console.WriteLine()



[<EntryPoint>]
let main args =
    // Get the current encoding so we can restore it.
    let originalOutputEncoding = Console.OutputEncoding

    try
        try
            let parsedArgs =
                match args.Length with
                | 2 ->
                    Some
                        {| setOutputEncodingToUnicode = true
                           rangeStart = uint.Parse(args[0], NumberStyles.HexNumber)
                           rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber) |}
                | 3 ->
                    let parseHexNumberOrThrow (value: string) parameterName =
                        (uint.TryParse(value, NumberStyles.HexNumber, null))
                        |> function
                        | (false, _) ->
                            invalidArg parameterName (String.Format("{0} is not a valid hexadecimal number.", value))
                        | (true, value) -> value

                    let setOutputEncodingToUnicode =
                        match bool.TryParse args[2] with
                        | true, value -> value
                        | false, _ -> true

                    Some
                        {| setOutputEncodingToUnicode = setOutputEncodingToUnicode
                           rangeStart = parseHexNumberOrThrow args[0] "rangeStart"
                           rangeEnd = parseHexNumberOrThrow args[1] "rangeEnd" |}
                | _ ->
                    printfn "Usage: %s <%s> <%s> [%s]" (Environment.GetCommandLineArgs()[0]) "startingCodePointInHex"
                        "endingCodePointInHex" "<setOutputEncodingToUnicode?{true|false, default:false}>"
                    None

            match parsedArgs with
            | None -> ()
            | Some parsedArgs ->
                if parsedArgs.setOutputEncodingToUnicode then
                    // 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 <- UnicodeEncoding(not BitConverter.IsLittleEndian, false)
                        printfn "\nOutput encoding set to UTF-16"

                    with :? IOException ->
                        printfn "Output encoding set to UTF-8"
                        Console.OutputEncoding <- UTF8Encoding()
                else
                    printfn "The console encoding is %s (code page %i)" (Console.OutputEncoding.EncodingName)
                        (Console.OutputEncoding.CodePage)

                displayRange parsedArgs.rangeStart parsedArgs.rangeEnd
        with :? ArgumentException as ex -> Console.WriteLine(ex.Message)
    finally
        // Restore console environment.
        Console.OutputEncoding <- originalOutputEncoding
    0

// 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  Ӱ  ӱ  Ӳ  ӳ - Ӵ  ӵ  Ӷ  ӷ -- Ӹ  ӹ  Ӻ  ӻ - Ӽ  ӽ  Ӿ  ӿ

一般的な操作

クラスには Console 、コンソール入力の読み取りとコンソール出力の書き込みのための次のメソッドが含まれています。

  • メソッドのオーバーロードは、個々の ReadKey 文字を読み取ります。

  • メソッドは ReadLine 、入力行全体を読み取ります。

  • メソッドオーバーロードは Write 、値型、文字の配列、またはオブジェクトのセットのインスタンスを書式設定された文字列または書式設定されていない文字列に変換し、その文字列をコンソールに書き込みます。

  • メソッド オーバーロードの WriteLine 並列セットは、オーバーロードと同じ文字列を Write 出力しますが、行終了文字列も追加します。

Consoleクラスには、次の操作を実行するためのメソッドとプロパティも含まれています。

  • 画面バッファーのサイズを取得または設定します。 BufferHeightプロパティと BufferWidth プロパティを使用すると、それぞれバッファーの高さと幅を取得または設定できますSetBufferSize。メソッドを使用すると、1 回のメソッド呼び出しでバッファー サイズを設定できます。

  • コンソール ウィンドウのサイズを取得または設定します。 WindowHeightプロパティと WindowWidth プロパティを使用すると、それぞれウィンドウの高さと幅を取得または設定できますSetWindowSize。メソッドを使用すると、1 回のメソッド呼び出しでウィンドウ サイズを設定できます。

  • カーソルのサイズを取得または設定します。 プロパティは CursorSize 、文字セル内のカーソルの高さを指定します。

  • 画面バッファーに対するコンソール ウィンドウの位置を取得または設定します。 WindowTopプロパティと WindowLeft プロパティを使用すると、コンソール ウィンドウに表示される画面バッファーの一番上の行と左端の列を取得または設定できます。メソッドを使用すると、SetWindowPositionこれらの値を 1 回のメソッド呼び出しで設定できます。

  • プロパティと CursorLeft プロパティを取得または設定してカーソルの位置をCursorTop取得または設定するか、 メソッドを呼び出してカーソルの位置をSetCursorPosition設定します。

  • または メソッドを呼び出して、画面バッファー内のデータを MoveBufferArea 移動または Clear クリアします。

  • プロパティと プロパティを使用して前景色と背景色をForegroundColorBackgroundColor取得または設定するか、 メソッドを呼び出ResetColorして背景と前景色を既定の色にリセットします。

  • メソッドを呼び出して、コンソール スピーカーを介してビープ音の音を Beep 再生します。

.NET Core の注意事項

デスクトップ上の.NET Frameworkでは、 Console クラスは、 および GetConsoleOutputCPによってGetConsoleCP返されるエンコーディングを使用します。これは通常、コード ページ エンコードです。 たとえば、カルチャが英語 (米国) のシステムでは、コード ページ 437 は既定で使用されるエンコードです。 ただし、.NET Core では、これらのエンコードの限定されたサブセットのみを使用できる場合があります。 この場合 Encoding.UTF8 、 はコンソールの既定のエンコードとして使用されます。

アプリが特定のコード ページ エンコードに依存している場合でも、メソッドを呼び出すConsole前に次の手順を実行して使用できるようにします。

  1. CodePagesEncodingProvider.Instance プロパティから、EncodingProvider オブジェクトを取得します。

  2. EncodingProvider オブジェクトを Encoding.RegisterProvider メソッドに渡すと、エンコーディング プロバイダーでサポートされているその他のエンコードを利用できるようになります。

その後、出力メソッドを呼び出すConsole前にエンコード プロバイダーを登録している場合、クラスは Console UTF8 ではなく既定のシステム エンコードを自動的に使用します。

プロパティ

BackgroundColor

コンソールの背景色を取得または設定します。

BufferHeight

バッファー領域の高さを取得または設定します。

BufferWidth

バッファー領域の幅を取得または設定します。

CapsLock

CapsLock がオンかオフかを示す値を取得します。

CursorLeft

バッファー領域におけるカーソルの列位置を取得または設定します。

CursorSize

文字セル内のカーソルの高さを取得または設定します。

CursorTop

バッファー領域におけるカーソルの行位置を取得または設定します。

CursorVisible

カーソルを表示するかどうかを示す値を取得または設定します。

Error

標準エラー出力ストリームを取得します。

ForegroundColor

コンソールの前景色を取得または設定します。

In

標準入力ストリームを取得します。

InputEncoding

コンソールが入力内容の読み取り時に使用するエンコーディングを取得または設定します。

IsErrorRedirected

エラー出力ストリームが標準エラー ストリームからリダイレクトされているかどうかを示す値を取得します。

IsInputRedirected

入力が標準入力ストリームからリダイレクトされているかどうかを示す値を取得します。

IsOutputRedirected

出力が標準出力ストリームからリダイレクトされているかどうかを示す値を取得します。

KeyAvailable

キーが押されたかどうか、つまり、押されたキーが入力ストリームに存在するかどうかを示す値を取得します。

LargestWindowHeight

現在のフォントおよび画面解像度に基づいて、コンソール ウィンドウの最大行数を取得します。

LargestWindowWidth

現在のフォントおよび画面解像度に基づいて、コンソール ウィンドウの最大列数を取得します。

NumberLock

NumLock がオンかオフかを示す値を取得します。

Out

標準出力ストリームを取得します。

OutputEncoding

コンソールが出力内容の書き込み時に使用するエンコーディングを取得または設定します。

Title

コンソールのタイトル バーに表示するタイトルを取得または設定します。

TreatControlCAsInput

Control 修飾キーと C コンソール キーの組み合わせ (Ctrl + C) を、通常の入力として扱うか、オペレーティング システムにより処理される割り込みとして扱うかを示す値を取得または設定します。

WindowHeight

コンソール ウィンドウ領域の高さを取得または設定します。

WindowLeft

コンソール ウィンドウ領域の左端の位置を、画面バッファーに対する相対位置として取得または設定します。

WindowTop

コンソール ウィンドウ領域の上端の位置を、画面バッファーに対する相対位置として取得または設定します。

WindowWidth

コンソール ウィンドウの幅を取得または設定します。

メソッド

Beep()

コンソールのスピーカーからビープ音を出します。

Beep(Int32, Int32)

周波数と時間を指定して、コンソールのスピーカーからビープ音を出します。

Clear()

コンソール バッファーおよび対応するコンソール ウィンドウをクリアします。

GetCursorPosition()

カーソルの位置を取得します。

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

画面バッファーの特定の領域を、指定した領域にコピーします。

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

画面バッファーの特定の領域を、指定した領域にコピーします。

OpenStandardError()

標準エラー ストリームを取得します。

OpenStandardError(Int32)

指定したバッファー サイズに設定された標準エラー ストリームを取得します。

OpenStandardInput()

標準入力ストリームを取得します。

OpenStandardInput(Int32)

指定したバッファー サイズに設定された標準入力ストリームを取得します。

OpenStandardOutput()

標準出力ストリームを取得します。

OpenStandardOutput(Int32)

指定したバッファー サイズに設定された標準出力ストリームを取得します。

Read()

標準入力ストリームから次の文字を読み取ります。

ReadKey()

ユーザーによって押された次の文字キーまたはファンクション キーを取得します。 押されたキーは、コンソール ウィンドウに表示されます。

ReadKey(Boolean)

ユーザーによって押された次の文字キーまたはファンクション キーを取得します。 押されたキーは、オプションでコンソール ウィンドウに表示されます。

ReadLine()

標準入力ストリームから次の 1 行分の文字を読み取ります。

ResetColor()

コンソールの前景色および背景色を既定値に設定します。

SetBufferSize(Int32, Int32)

画面バッファー領域の高さと幅を指定された値に設定します。

SetCursorPosition(Int32, Int32)

カーソルの位置を設定します。

SetError(TextWriter)

Error プロパティを、指定した TextWriter オブジェクトに設定します。

SetIn(TextReader)

In プロパティを、指定した TextReader オブジェクトに設定します。

SetOut(TextWriter)

Out プロパティを TextWriter オブジェクトをターゲットとするように設定します。

SetWindowPosition(Int32, Int32)

画面バッファーに対するコンソール ウィンドウの相対位置を設定します。

SetWindowSize(Int32, Int32)

コンソール ウィンドウの高さと幅を指定された値に設定します。

Write(Boolean)

指定した Boolean 値のテキスト形式を標準出力ストリームに書き込みます。

Write(Char)

指定した Unicode 文字値を標準出力ストリームに書き込みます。

Write(Char[])

指定した Unicode 文字配列を標準出力ストリームに書き込みます。

Write(Char[], Int32, Int32)

指定した Unicode 文字の部分配列を標準出力ストリームに書き込みます。

Write(Decimal)

指定した Decimal 値のテキスト形式を標準出力ストリームに書き込みます。

Write(Double)

指定した倍精度浮動小数点値のテキスト形式を標準出力ストリームに書き込みます。

Write(Int32)

指定した 32 ビット符号付き整数値のテキスト形式を標準出力ストリームに書き込みます。

Write(Int64)

指定した 64 ビット符号付き整数値のテキスト形式を標準出力ストリームに書き込みます。

Write(Object)

指定したオブジェクトのテキスト形式を標準出力ストリームに書き込みます。

Write(Single)

指定した単精度浮動小数点値のテキスト形式を標準出力ストリームに書き込みます。

Write(String)

指定した文字列値を標準出力ストリームに書き込みます。

Write(String, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込みます。

Write(String, Object, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込みます。

Write(String, Object, Object, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込みます。

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

指定した書式情報を使用して、指定したオブジェクトのテキスト表現と可変長パラメーター リストを標準出力ストリームに書き込みます。

Write(String, Object[])

指定された書式情報を使用して、指定したオブジェクト配列のテキスト表現を標準出力ストリームに書き込みます。

Write(UInt32)

指定した 32 ビット符号なし整数値のテキスト形式を標準出力ストリームに書き込みます。

Write(UInt64)

指定した 64 ビット符号なし整数値のテキスト形式を標準出力ストリームに書き込みます。

WriteLine()

現在の行終端記号を標準出力ストリームに書き込みます。

WriteLine(Boolean)

指定した Boolean 値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Char)

指定した Unicode 文字を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Char[])

指定した Unicode 文字配列を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Char[], Int32, Int32)

指定した Unicode 文字の部分配列を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Decimal)

指定した Decimal 値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Double)

指定した倍精度浮動小数点値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Int32)

指定した 32 ビット符号付き整数値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Int64)

指定した 64 ビット符号付き整数値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Object)

指定したオブジェクトのテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(Single)

指定した単精度浮動小数点値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(String)

指定した文字列値を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(String, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(String, Object, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(String, Object, Object, Object)

指定した書式情報を使用して、指定したオブジェクトのテキスト表現を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

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

指定した書式情報を使用して、指定したオブジェクトのテキスト表現と可変長パラメーター リストを標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(String, Object[])

指定した書式情報を使用して、指定したオブジェクト配列のテキスト表現を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(UInt32)

指定した 32 ビット符号なし整数値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

WriteLine(UInt64)

指定した 64 ビット符号なし整数値のテキスト形式を標準出力ストリームに書き込み、続けて現在の行終端記号を書き込みます。

events

CancelKeyPress

Control の修飾子キー (Ctrl) と C コンソール キー (c) または中断キーが同時にプッシュされた場合 (Ctrl + C または Ctrl + Break) に発生します。

適用対象

スレッド セーフ

この型はスレッド セーフです。