Classe System.Console
Questo articolo fornisce osservazioni supplementari alla documentazione di riferimento per questa API.
La console è una finestra del sistema operativo in cui gli utenti interagiscono con il sistema operativo o con un'applicazione console basata su testo immettendo l'input di testo tramite la tastiera del computer e leggendo l'output di testo dal terminale del computer. Nel sistema operativo Windows, ad esempio, la console viene chiamata finestra del prompt dei comandi e accetta i comandi MS-DOS. La Console classe fornisce il supporto di base per le applicazioni che leggono caratteri da e scrivono caratteri nella console.
Flussi di I/O della console
All'avvio di un'applicazione console, il sistema operativo associa automaticamente tre flussi di I/O alla console: flusso di input standard, flusso di output standard e flusso di output degli errori standard. L'applicazione può leggere l'input dell'utente dal flusso di input standard; scrivere dati normali nel flusso di output standard; e scrivere i dati degli errori nel flusso di output degli errori standard. Questi flussi vengono presentati all'applicazione come valori delle Console.Inproprietà , Console.Oute Console.Error .
Per impostazione predefinita, il valore della In proprietà è un System.IO.TextReader oggetto che rappresenta la tastiera e i valori delle Out proprietà e Error sono System.IO.TextWriter oggetti che rappresentano una finestra della console. Tuttavia, è possibile impostare queste proprietà su flussi che non rappresentano la finestra della console o la tastiera; Ad esempio, è possibile impostare queste proprietà su flussi che rappresentano i file. Per reindirizzare l'input standard, l'output standard o il flusso di errore standard, chiamare rispettivamente il Console.SetInmetodo , Console.SetOuto Console.SetError . Le operazioni di I/O che usano questi flussi vengono sincronizzate, il che significa che più thread possono leggere o scrivere nei flussi. Ciò significa che i metodi normalmente asincroni, ad esempio TextReader.ReadLineAsync, vengono eseguiti in modo sincrono se l'oggetto rappresenta un flusso della console.
Nota
Non usare la classe per visualizzare l'output Console in applicazioni automatiche, ad esempio applicazioni server. Le chiamate a metodi come Console.Write e Console.WriteLine non hanno alcun effetto nelle applicazioni GUI.
Console I membri della classe che funzionano normalmente quando il flusso sottostante viene indirizzato a una console potrebbe generare un'eccezione se il flusso viene reindirizzato, ad esempio, a un file. Programmare l'applicazione per intercettare System.IO.IOException le eccezioni se si reindirizza un flusso standard. È anche possibile usare le IsOutputRedirectedproprietà , IsInputRedirectede IsErrorRedirected per determinare se un flusso standard viene reindirizzato prima di eseguire un'operazione che genera un'eccezione System.IO.IOException .
A volte è utile chiamare in modo esplicito i membri degli oggetti flusso rappresentati dalle Inproprietà , Oute Error . Per impostazione predefinita, ad esempio, il Console.ReadLine metodo legge l'input dal flusso di input standard. Analogamente, il Console.WriteLine metodo scrive i dati nel flusso di output standard e i dati sono seguiti dalla stringa di terminazione di riga predefinita, disponibile in Environment.NewLine. Tuttavia, la Console classe non fornisce un metodo corrispondente per scrivere dati nel flusso di output degli errori standard o una proprietà per modificare la stringa di terminazione della riga per i dati scritti in tale flusso.
È possibile risolvere questo problema impostando la TextWriter.NewLine proprietà della proprietà o Error su un'altra stringa di Out terminazione della riga. Ad esempio, l'istruzione C# seguente imposta la stringa di terminazione della riga per il flusso di output degli errori standard su due sequenze di ritorno a capo e avanzamento riga:
Console.Error.NewLine = "\r\n\r\n";
È quindi possibile chiamare in modo esplicito il WriteLine metodo dell'oggetto flusso di output degli errori, come nell'istruzione C# seguente:
Console.Error.WriteLine();
Buffer dello schermo e finestra della console
Due funzionalità strettamente correlate della console sono il buffer dello schermo e la finestra della console. Il testo viene effettivamente letto o scritto in flussi di proprietà della console, ma sembra essere letto o scritto in un'area di proprietà della console denominata buffer dello schermo. Il buffer dello schermo è un attributo della console ed è organizzato come griglia rettangolare di righe e colonne in cui ogni intersezione della griglia, o cella di caratteri, può contenere un carattere. Ogni carattere ha un proprio colore di primo piano e ogni cella di caratteri ha il proprio colore di sfondo.
Il buffer dello schermo viene visualizzato tramite un'area rettangolare denominata finestra della console. La finestra della console è un altro attributo della console; non è la console stessa, ovvero una finestra del sistema operativo. La finestra della console è disposta in righe e colonne, è minore o uguale alla dimensione del buffer dello schermo e può essere spostata per visualizzare aree diverse del buffer dello schermo sottostante. Se il buffer dello schermo è maggiore della finestra della console, la console visualizza automaticamente le barre di scorrimento in modo che la finestra della console possa essere riposizionata sull'area del buffer dello schermo.
Un cursore indica la posizione del buffer dello schermo in cui il testo è attualmente letto o scritto. Il cursore può essere nascosto o reso visibile e l'altezza può essere modificata. Se il cursore è visibile, la posizione della finestra della console viene spostata automaticamente in modo che il cursore sia sempre visualizzato.
L'origine delle coordinate delle celle di caratteri nel buffer dello schermo è l'angolo superiore sinistro e le posizioni del cursore e della finestra della console vengono misurate rispetto a tale origine. Usare indici in base zero per specificare le posizioni; ovvero specificare la riga più in alto come riga 0 e la colonna più a sinistra come colonna 0. Il valore massimo per gli indici di riga e colonna è Int16.MaxValue.
Supporto Unicode per la console
In generale, la console legge l'input e scrive l'output usando la tabella codici della console corrente, definita dalle impostazioni locali di sistema per impostazione predefinita. Una tabella codici può gestire solo un subset di caratteri Unicode disponibili, quindi se si tenta di visualizzare caratteri non mappati da una determinata tabella codici, la console non sarà in grado di visualizzare tutti i caratteri o di rappresentarli in modo accurato. L'esempio seguente illustra questo problema. Tenta di visualizzare i caratteri dell'alfabeto cirillico da U+0410 a U+044F nella console. Se si esegue l'esempio in un sistema che usa la tabella codici della console 437, ogni carattere viene sostituito da un punto interrogativo (?), perché i caratteri cirillici non vengono mappati ai caratteri nella tabella codici 437.
using System;
public class Example3
{
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
//
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Oltre a supportare le tabelle codici, la classe supporta la Console codifica UTF-8 con la UTF8Encoding classe . A partire da .NET Framework 4.5, la classe supporta anche la Console codifica UTF-16 con la UnicodeEncoding classe . Per visualizzare i caratteri Unicode nella console. impostare la OutputEncoding proprietà su UTF8Encoding o UnicodeEncoding.
Il supporto per i caratteri Unicode richiede al codificatore di riconoscere un carattere Unicode specifico e richiede anche un tipo di carattere con i glifi necessari per eseguire il rendering di tale carattere. Per visualizzare correttamente i caratteri Unicode nella console, il tipo di carattere della console deve essere impostato su un tipo di carattere non raster o TrueType, ad esempio Consolas o Lucida Console. Nell'esempio seguente viene illustrato come modificare a livello di codice il tipo di carattere da un tipo di carattere raster a Lucida Console.
using System;
using System.Runtime.InteropServices;
public class Example2
{
[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 Example5
' <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
Tuttavia, i tipi di carattere TrueType possono visualizzare solo un subset di glifi. Ad esempio, il carattere Lucida Console visualizza solo 643 dei circa 64.000 caratteri disponibili da U+0021 a U+FB02. Per visualizzare i caratteri supportati da un tipo di carattere specifico, aprire l'applet Font in Pannello di controllo, scegliere l'opzione Trova un carattere e scegliere il tipo di carattere il cui set di caratteri si desidera esaminare nell'elenco Carattere della finestra Mappa caratteri.
Windows usa il collegamento dei tipi di carattere per visualizzare glifi non disponibili in un tipo di carattere specifico. Per informazioni sul collegamento dei tipi di carattere per visualizzare set di caratteri aggiuntivi, vedere Passaggio della globalizzazione: Tipi di carattere. I tipi di carattere collegati sono definiti nella sottochiave HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink del Registro di sistema. Ogni voce associata a questa sottochiave corrisponde al nome di un tipo di carattere di base e il relativo valore è una matrice di stringhe che definisce i file di carattere e i tipi di carattere collegati al tipo di carattere di base. Ogni membro della matrice definisce un tipo di carattere collegato e prende il formato font-file-name, font-name. Nell'esempio seguente viene illustrato come definire a livello di codice un tipo di carattere collegato denominato SimSun in un file di carattere denominato simsun.ttc che visualizza caratteri Han semplificati.
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 Example2
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)) Then
' 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()
Il supporto Unicode per la console presenta le limitazioni seguenti:
La codifica UTF-32 non è supportata. Le uniche codifiche Unicode supportate sono UTF-8 e UTF-16, rappresentate rispettivamente dalle UTF8Encoding classi e UnicodeEncoding .
L'output bidirezionale non è supportato.
La visualizzazione di caratteri al di fuori del piano multilingue di base (ovvero di coppie di surrogati) non è supportata, anche se sono definite in un file di tipo di carattere collegato.
La visualizzazione di caratteri in script complessi non è supportata.
La combinazione di sequenze di caratteri (ovvero i caratteri costituiti da un carattere di base e uno o più caratteri combinati) vengono visualizzati come caratteri separati. Per ovviare a questa limitazione, è possibile normalizzare la stringa da visualizzare chiamando il metodo prima di inviare l'output String.Normalize alla console. Nell'esempio seguente viene visualizzata una stringa contenente la sequenza di caratteri di combinazione U+0061 U+0308 nella console come due caratteri prima che la stringa di output venga normalizzata e come singolo carattere dopo la chiamata del String.Normalize metodo.
using System; using System.IO; public class Example1 { 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 Example3 Public Sub Main() Dim chars() As Char = {ChrW(&H61), ChrW(&H308)} 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" // ä
La normalizzazione è una soluzione praticabile solo se lo standard Unicode per il carattere include una forma pre-composta che corrisponde a una particolare sequenza di caratteri di combinazione.
Se un tipo di carattere fornisce un glifo per un punto di codice nell'area di utilizzo privato, verrà visualizzato tale glifo. Tuttavia, poiché i caratteri nell'area di utilizzo privato sono specifici dell'applicazione, questo potrebbe non essere il glifo previsto.
Nell'esempio seguente viene visualizzato un intervallo di caratteri Unicode nella console. L'esempio accetta tre parametri della riga di comando: l'inizio dell'intervallo da visualizzare, la fine dell'intervallo da visualizzare e se usare la codifica della console corrente (false
) o la codifica UTF-16 (true
). Si presuppone che la console usi un tipo di carattere 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 Ӱ ӱ Ӳ ӳ - Ӵ ӵ Ӷ ӷ -- Ӹ ӹ Ӻ ӻ - Ӽ ӽ Ӿ ӿ
Operazioni comuni
La Console classe contiene i metodi seguenti per leggere l'input della console e scrivere l'output della console:
Gli overload del ReadKey metodo leggono un singolo carattere.
Il ReadLine metodo legge un'intera riga di input.
L'overload del Write metodo converte un'istanza di un tipo valore, una matrice di caratteri o un set di oggetti in una stringa formattata o non formattata e quindi scrive tale stringa nella console.
Un set parallelo di overload del WriteLine metodo restituisce la stessa stringa degli Write overload, ma aggiunge anche una stringa di terminazione della riga.
La Console classe contiene anche metodi e proprietà per eseguire le operazioni seguenti:
Ottiene o imposta le dimensioni del buffer dello schermo. Le BufferHeight proprietà e BufferWidth consentono di ottenere o impostare rispettivamente l'altezza e la larghezza del buffer e il SetBufferSize metodo consente di impostare le dimensioni del buffer in una singola chiamata al metodo.
Ottiene o imposta le dimensioni della finestra della console. Le WindowHeight proprietà e WindowWidth consentono di ottenere o impostare rispettivamente l'altezza e la larghezza della finestra e il SetWindowSize metodo consente di impostare le dimensioni della finestra in una singola chiamata al metodo.
Ottiene o imposta le dimensioni del cursore. La CursorSize proprietà specifica l'altezza del cursore in una cella di caratteri.
Ottiene o imposta la posizione della finestra della console rispetto al buffer dello schermo. Le WindowTop proprietà e WindowLeft consentono di ottenere o impostare la riga superiore e la colonna più a sinistra del buffer dello schermo visualizzato nella finestra della console e il SetWindowPosition metodo consente di impostare questi valori in una singola chiamata al metodo.
Ottiene o imposta la posizione del cursore recuperando o impostando le CursorTop proprietà e CursorLeft oppure impostando la posizione del cursore chiamando il SetCursorPosition metodo .
Spostare o cancellare i dati nel buffer dello schermo chiamando il MoveBufferArea metodo o Clear .
Ottenere o impostare i colori di primo piano e di sfondo usando le ForegroundColor proprietà e BackgroundColor oppure reimpostare lo sfondo e il primo piano sui colori predefiniti chiamando il ResetColor metodo .
Riprodurre il suono di un segnale acustico tramite l'altoparlante della console chiamando il Beep metodo .
Note su .NET Core
In .NET Framework sul desktop, la Console classe usa la codifica restituita da GetConsoleCP
e GetConsoleOutputCP
, che in genere è una codifica della tabella codici. Ad esempio, nei sistemi le cui impostazioni cultura sono inglese (Stati Uniti), la tabella codici 437 è la codifica usata per impostazione predefinita. Tuttavia, .NET Core può rendere disponibile solo un subset limitato di queste codifiche. In questo caso, Encoding.UTF8 viene usato come codifica predefinita per la console.
Se l'app dipende da codifiche specifiche della tabella codici, puoi comunque renderle disponibili eseguendo le operazioni seguenti prima di chiamare qualsiasi Console metodo:
Recuperare l'oggetto EncodingProvider dalla CodePagesEncodingProvider.Instance proprietà .
Passare l'oggetto EncodingProvider al Encoding.RegisterProvider metodo per rendere disponibili le codifiche aggiuntive supportate dal provider di codifica.
La Console classe userà quindi automaticamente la codifica di sistema predefinita anziché UTF8, purché il provider di codifica sia stato registrato prima di chiamare qualsiasi Console metodo di output.
Esempi
Nell'esempio seguente viene illustrato come leggere i dati da e scrivere dati in, i flussi di input e output standard. Si noti che questi flussi possono essere reindirizzati usando i SetIn metodi e SetOut .
using System;
public class Example4
{
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 Example4
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!