Console 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示控制台应用程序的标准输入流、输出流和错误流。 此类不能被继承。
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
示例
下面的示例演示如何从标准输入和输出流中读取数据以及向其中写入数据。 请注意,这些流可以使用和方法进行重定向 SetIn SetOut 。
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 流
控制台应用程序启动时,操作系统会自动将三个 I/O 流与控制台关联:标准输入流、标准输出流和标准错误输出流。 应用程序可以从标准输入流中读取用户输入;将正常数据写入标准输出流;和 将错误数据写入标准错误输出流。 这些流作为 、 和 属性的值 Console.In 呈现 Console.Out 给 Console.Error 应用程序。
默认情况下,属性的值是表示键盘的对象,和 属性的值 In System.IO.TextReader Out Error 是 System.IO.TextWriter 表示控制台窗口的对象。 但是,可以将这些属性设置为不表示控制台窗口或键盘的流;例如,可以将这些属性设置为表示文件的流。 若要重定向标准输入、标准输出或标准错误流,请分别调用 Console.SetIn 、 Console.SetOut 或 Console.SetError 方法。 使用这些流的 I/O 操作是同步的,这意味着多个线程可以从流中读取或写入这些流。 这意味着,如果 对象表示控制台流,则通常异步的方法(如 ) TextReader.ReadLineAsync 将同步执行。
备注
请勿使用 Console 类在无人参与的应用程序(如服务器应用程序)中显示输出。 对 和 等方法 Console.Write 的 Console.WriteLine 调用在 GUI 应用程序中不起作用。
Console 当基础流定向到控制台时正常工作的类成员可能会引发异常(例如,将流重定向到文件)。 如果重定向标准流,请对应用程序进行编程 System.IO.IOException 以捕获异常。 还可使用 、 和 属性来确定在执行引发异常的操作之前是否重定向 IsOutputRedirected IsInputRedirected IsErrorRedirected 标准 System.IO.IOException 流。
有时,显式调用 、 和 属性表示的流对象的成员 In Out Error 很有用。 例如,默认情况下, Console.ReadLine 方法从标准输入流中读取输入。 同样, 方法将数据写入标准输出流,数据后跟默认行终止字符串,可在 Console.WriteLine 找到 Environment.NewLine 。 但是, 类不提供相应的方法将数据写入标准错误输出流,也不提供 属性来更改写入该流的数据的行 Console 终止字符串。
可以通过将 或 属性的 属性设置为另一行终止字符串 TextWriter.NewLine Out Error 来解决此问题。 例如,以下 C# 语句将标准错误输出流的行终止字符串设置为两个回车符和换行序列:
Console.Error.NewLine = "\r\n\r\n";
然后,可以显式调用 WriteLine 错误输出流对象的 方法,如以下 C# 语句所示:
Console.Error.WriteLine();
屏幕缓冲区和控制台窗口
控制台的两个密切相关的功能是屏幕缓冲区和控制台窗口。 文本实际上是从控制台拥有的流中读取或写入的,但似乎从控制台拥有的区域(称为屏幕缓冲区)读取或写入。 屏幕缓冲区是控制台的一个属性,并组织为行和列的矩形网格,其中每个网格交集或字符单元格可以包含字符。 每个字符都有自己的前景色,每个字符单元格都有自己的背景色。
屏幕缓冲区通过名为控制台窗口的矩形区域进行查看。 控制台窗口是控制台的另一个属性;不是控制台本身,它是操作系统窗口。 控制台窗口按行和列排列,小于或等于屏幕缓冲区的大小,可以移动该窗口以查看基础屏幕缓冲区的不同区域。 如果屏幕缓冲区大于控制台窗口,控制台将自动显示滚动条,以便控制台窗口可以重新定位到屏幕缓冲区上。
光标指示当前读取或写入文本的屏幕缓冲区位置。 光标可以隐藏或可见,其高度也可以更改。 如果光标可见,控制台窗口位置将自动移动,使光标始终处于视图中。
屏幕缓冲区中字符单元格坐标的原点位于左上角,光标和控制台窗口的位置相对于该原点进行测量。 使用从零开始索引指定位置;也就是说,将最顶部的行指定为第 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 字符。 将 属性 OutputEncoding 设置为 或 UTF8Encoding UnicodeEncoding 。
支持 Unicode 字符需要编码器识别特定的 Unicode 字符,并且还需要具有呈现该字符所需的字形的字体。 若要成功向控制台显示 Unicode 字符,必须将控制台字体设置为非 raster 或 TrueType 字体,例如 Consolas 或 Lucida 控制台。 以下示例演示如何以编程方式将字体从 raster 字体更改为 Lucida 控制台。
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 的链接字体,该字体位于显示简体 Han 字符的名为 simsun.ttc 的字体文件中。
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,它们分别由 和 UTF8Encoding UnicodeEncoding 类表示。
不支持双向输出。
基本多语言平面外部的字符 (,即不支持) 代理项对的字符,即使它们是在链接的字体文件中定义的。
不支持在复杂脚本中显示字符。
组合字符序列 (,即由基字符和一个或多个组合字符组成的字符) 显示为单独的字符。 若要处理此限制,可以通过在将输出发送到控制台之前调用 方法来规范化要 String.Normalize 显示的字符串。 在下面的示例中,包含组合字符序列 U+0061 U+0308 的字符串在输出字符串规范化之前显示为两个字符,在调用 方法后显示为单个 String.Normalize 字符。
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 字符范围。 该示例接受三个命令行参数:要显示的范围的开始、要显示的范围的末尾,以及是使用当前控制台编码 () 还是 false
UTF-16 编码 true
() 。 它假定控制台使用的是 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 包含以下用于读取控制台输入和写入控制台输出的方法:
类 Console 还包含用于执行以下操作的方法和属性:
获取或设置屏幕缓冲区的大小。 和 BufferHeight BufferWidth 属性允许分别获取或设置缓冲区高度和宽度,并且 方法允许你在单个方法调用中 SetBufferSize 设置缓冲区大小。
获取或设置控制台窗口的大小。 和 属性允许分别获取或设置窗口高度和宽度,并且 方法允许你在单个方法调用 WindowHeight WindowWidth SetWindowSize 中设置窗口大小。
获取或设置游标的大小。 CursorSize属性指定字符单元格中光标的高度。
获取或设置控制台窗口相对于屏幕缓冲区的位置。 和 属性可用于获取或设置控制台窗口中出现的屏幕缓冲区的顶部行和最左侧列,并且 方法允许你在单个方法调用中 WindowTop WindowLeft SetWindowPosition 设置这些值。
通过获取或设置 和 属性获取或设置游标的位置,或者通过调用 方法 CursorTop CursorLeft 设置光标 SetCursorPosition 的位置。
通过调用或方法,在屏幕缓冲区中移动或清除数据 MoveBufferArea Clear 。
通过使用和属性获取或设置前景色和背景 ForegroundColor 色 BackgroundColor ,或通过调用方法将背景和前景重置为其默认颜色 ResetColor 。
通过调用方法,通过控制台扬声器播放提示音 Beep 。
.NET Core 说明
在桌面上的 .NET Framework 中, Console 类使用和返回的编码 GetConsoleCP
GetConsoleOutputCP
,这通常是一种代码页编码。 例如,在区域性为英语 (美国) 的系统上,代码页437是默认情况下使用的编码。 但是,.NET Core 只能提供这些编码的有限子集。 对于这种情况, Encoding.UTF8 将用作控制台的默认编码。
如果你的应用程序依赖于特定的代码页编码,你仍可以在调用任何方法 之前 执行以下操作,使其可用 Console :
向项目添加对 System.Text.Encoding.CodePages.dll 程序集的引用。
EncodingProvider从属性中检索对象 CodePagesEncodingProvider.Instance 。
将 EncodingProvider 对象传递给 Encoding.RegisterProvider 方法,以使编码提供程序支持其他编码。
Console类随后会自动使用默认系统编码,而不是 UTF8,前提是在调用任何输出方法之前已注册了编码提供程序 Console 。
属性
BackgroundColor |
获取或设置控制台的背景色。 |
BufferHeight |
获取或设置缓冲区的高度。 |
BufferWidth |
获取或设置缓冲区的宽度。 |
CapsLock |
获取一个值,该值指示 Caps Lock 键盘切换键是打开的还是关闭的。 |
CursorLeft |
获取或设置光标在缓冲区中的列位置。 |
CursorSize |
获取或设置光标在字符单元格中的高度。 |
CursorTop |
获取或设置光标在缓冲区中的行位置。 |
CursorVisible |
获取或设置一个值,用以指示光标是否可见。 |
Error |
获取标准错误输出流。 |
ForegroundColor |
获取或设置控制台的前景色。 |
In |
获取标准输入流。 |
InputEncoding |
获取或设置控制台用于读取输入的编码。 |
IsErrorRedirected |
获取指示错误输出流是否已经从标准错误流被再定位的值。 |
IsInputRedirected |
获取指示输入是否已从标准输入流中重定向的值。 |
IsOutputRedirected |
获取指示输出是否已从标准输入流中重定向的值。 |
KeyAvailable |
获取一个值,该值指示按键操作在输入流中是否可用。 |
LargestWindowHeight |
根据当前字体和屏幕分辨率获取控制台窗口可能具有的最大行数。 |
LargestWindowWidth |
根据当前字体和屏幕分辨率获取控制台窗口可能具有的最大列数。 |
NumberLock |
获取一个值,该值指示 Num Lock 键盘切换键是打开的还是关闭的。 |
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() |
从标准输入流读取下一行字符。 |
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) |
将指定的布尔值的文本表示形式写入标准输出流。 |
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) |
将指定布尔值的文本表示形式(后跟当前行终止符)写入标准输出流。 |
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 位无符号的整数值的文本表示(后跟当前行的结束符)写入标准输出流。 |
事件
CancelKeyPress |
当 Control 修改键 (Ctrl) 和 C console 键 (C) 或 Break 键同时按住(Ctrl+C 或 Ctrl+Break)时发生。 |
适用于
线程安全性
此类型是线程安全的。