本文整理汇总了C#中System.Console类的典型用法代码示例。如果您正苦于以下问题:C# Console类的具体用法?C# Console怎么用?C# Console使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Console类属于System命名空间,在下文中一共展示了Console类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
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("!");
}
}
输出:
Hello World! Enter your name: James Good day, James!
示例2: Main
//引入命名空间
using System;
public class Example
{
public static void Main()
{
// Create a Char array for the modern Cyrillic alphabet,
// from U+0410 to U+044F.
int nChars = 0x044F - 0x0410 + 1;
char[] chars = new char[nChars];
ushort codePoint = 0x0410;
for (int ctr = 0; ctr < chars.Length; ctr++) {
chars[ctr] = Convert.ToChar(codePoint);
codePoint++;
}
Console.WriteLine("Current code page: {0}\n",
Console.OutputEncoding.CodePage);
// Display the characters.
foreach (var ch in chars) {
Console.Write("{0} ", ch);
if (Console.CursorLeft >= 70)
Console.WriteLine();
}
}
}
输出:
Current code page: 437 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
示例3: GetStdHandle
//引入命名空间
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];
}
}
示例4: Main
//引入命名空间
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();
}
}
示例5: Main
//引入命名空间
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);
}
}
输出:
a" ä
示例6: Main
//引入命名空间
using System;
using System.IO;
using System.Globalization;
using System.Text;
public static class DisplayChars
{
private static void Main(string[] args)
{
uint rangeStart = 0;
uint rangeEnd = 0;
bool setOutputEncodingToUnicode = true;
// Get the current encoding so we can restore it.
Encoding originalOutputEncoding = Console.OutputEncoding;
try
{
switch(args.Length)
{
case 2:
rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
setOutputEncodingToUnicode = true;
break;
case 3:
if (! uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0]));
if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1]));
bool.TryParse(args[2], out setOutputEncodingToUnicode);
break;
default:
Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]",
Environment.GetCommandLineArgs()[0],
"startingCodePointInHex",
"endingCodePointInHex",
"<setOutputEncodingToUnicode?{true|false, default:false}>");
return;
}
if (setOutputEncodingToUnicode) {
// This won't work before .NET Framework 4.5.
try {
// Set encoding using endianness of this system.
// We're interested in displaying individual Char objects, so
// we don't want a Unicode BOM or exceptions to be thrown on
// invalid Char values.
Console.OutputEncoding = new UnicodeEncoding(! BitConverter.IsLittleEndian, false);
Console.WriteLine("\nOutput encoding set to UTF-16");
}
catch (IOException) {
Console.OutputEncoding = new UTF8Encoding();
Console.WriteLine("Output encoding set to UTF-8");
}
}
else {
Console.WriteLine("The console encoding is {0} (code page {1})",
Console.OutputEncoding.EncodingName,
Console.OutputEncoding.CodePage);
}
DisplayRange(rangeStart, rangeEnd);
}
catch (ArgumentException ex) {
Console.WriteLine(ex.Message);
}
finally {
// Restore console environment.
Console.OutputEncoding = originalOutputEncoding;
}
}
public static void DisplayRange(uint start, uint end)
{
const uint upperRange = 0x10FFFF;
const uint surrogateStart = 0xD800;
const uint surrogateEnd = 0xDFFF;
if (end <= start) {
uint t = start;
start = end;
end = t;
}
// Check whether the start or end range is outside of last plane.
if (start > upperRange)
throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
start, upperRange));
if (end > upperRange)
throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
end, upperRange));
// Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd ))
throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}",
start, end, surrogateStart, surrogateEnd));
uint last = RoundUpToMultipleOf(0x10, end);
uint first = RoundDownToMultipleOf(0x10, start);
uint rows = (last - first) / 0x10;
for (uint r = 0; r < rows; ++r) {
// Display the row header.
Console.Write("{0:x5} ", first + 0x10 * r);
for (uint c = 0; c < 0x10; ++c) {
uint cur = (first + 0x10 * r + c);
if (cur < start) {
Console.Write(" {0} ", Convert.ToChar(0x20));
}
else if (end < cur) {
Console.Write(" {0} ", Convert.ToChar(0x20));
}
else {
// the cast to int is safe, since we know that val <= upperRange.
String chars = Char.ConvertFromUtf32( (int) cur);
// Display a space for code points that are not valid characters.
if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
UnicodeCategory.OtherNotAssigned)
Console.Write(" {0} ", Convert.ToChar(0x20));
// Display a space for code points in the private use area.
else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
UnicodeCategory.PrivateUse)
Console.Write(" {0} ", Convert.ToChar(0x20));
// Is surrogate pair a valid character?
// Note that the console will interpret the high and low surrogate
// as separate (and unrecognizable) characters.
else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
UnicodeCategory.OtherNotAssigned)
Console.Write(" {0} ", Convert.ToChar(0x20));
else
Console.Write(" {0} ", chars);
}
switch (c) {
case 3: case 11:
Console.Write("-");
break;
case 7:
Console.Write("--");
break;
}
}
Console.WriteLine();
if (0 < r && r % 0x10 == 0)
Console.WriteLine();
}
}
private static uint RoundUpToMultipleOf(uint b, uint u)
{
return RoundDownToMultipleOf(b, u) + b;
}
private static uint RoundDownToMultipleOf(uint b, uint u)
{
return u - (u % b);
}
}
// If the example is run with the command line
// DisplayChars 0400 04FF true
// the example displays the Cyrillic character set as follows:
// Output encoding set to UTF-16
// 00400 Ѐ Ё Ђ Ѓ - Є Ѕ І Ї -- Ј Љ Њ Ћ - Ќ Ѝ Ў Џ
// 00410 А Б В Г - Д Е Ж З -- И Й К Л - М Н О П
// 00420 Р С Т У - Ф Х Ц Ч -- Ш Щ Ъ Ы - Ь Э Ю Я
// 00430 а б в г - д е ж з -- и й к л - м н о п
// 00440 р с т у - ф х ц ч -- ш щ ъ ы - ь э ю я
// 00450 ѐ ё ђ ѓ - є ѕ і ї -- ј љ њ ћ - ќ ѝ ў џ
// 00460 Ѡ ѡ Ѣ ѣ - Ѥ ѥ Ѧ ѧ -- Ѩ ѩ Ѫ ѫ - Ѭ ѭ Ѯ ѯ
// 00470 Ѱ ѱ Ѳ ѳ - Ѵ ѵ Ѷ ѷ -- Ѹ ѹ Ѻ ѻ - Ѽ ѽ Ѿ ѿ
// 00480 Ҁ ҁ ҂ ҃ - ҄ ҅ ҆ ҇ -- ҈ ҉ Ҋ ҋ - Ҍ ҍ Ҏ ҏ
// 00490 Ґ ґ Ғ ғ - Ҕ ҕ Җ җ -- Ҙ ҙ Қ қ - Ҝ ҝ Ҟ ҟ
// 004a0 Ҡ ҡ Ң ң - Ҥ ҥ Ҧ ҧ -- Ҩ ҩ Ҫ ҫ - Ҭ ҭ Ү ү
// 004b0 Ұ ұ Ҳ ҳ - Ҵ ҵ Ҷ ҷ -- Ҹ ҹ Һ һ - Ҽ ҽ Ҿ ҿ
// 004c0 Ӏ Ӂ ӂ Ӄ - ӄ Ӆ ӆ Ӈ -- ӈ Ӊ ӊ Ӌ - ӌ Ӎ ӎ ӏ
// 004d0 Ӑ ӑ Ӓ ӓ - Ӕ ӕ Ӗ ӗ -- Ә ә Ӛ ӛ - Ӝ ӝ Ӟ ӟ
// 004e0 Ӡ ӡ Ӣ ӣ - Ӥ ӥ Ӧ ӧ -- Ө ө Ӫ ӫ - Ӭ ӭ Ӯ ӯ
// 004f0 Ӱ ӱ Ӳ ӳ - Ӵ ӵ Ӷ ӷ -- Ӹ ӹ Ӻ ӻ - Ӽ ӽ Ӿ ӿ