How do I read special characters (0x80 … 0x9F) from the Windows console in C#?

一世执手 提交于 2019-12-11 11:00:18

问题


I've finally solved the issue of writing special characters (0x80...0x9F) to the Windows console with the help of David:

  1. The output encoding has to be set to UTF-8.
  2. The font used by the console should be something like Consolas.

Now I'd like to be able to read back text which contains special characters found in the 0x80-0x9F range (using the Windows 1252 encoding), such as the EURO sign (€):

string text = System.Console.ReadLine ();

returns null whenever I type one of the special characters. I tried naively to set the InputEncoding to UTF8:

System.Console.InputEncoding = System.Text.Encoding.UTF8;

but this does not help.


回答1:


You could set the input code page of your console application to read those special characters. There is a Win32 api called SetConsoleCP to set the input code page. In the following example I use Windows-1252 code page:

[DllImport("kernel32.dll")]
private static extern bool SetConsoleCP(uint wCodePageID);

static void Main(string[] args)
{
  SetConsoleCP((uint)1252);
  Console.OutputEncoding = Encoding.UTF8;
  System.Console.Out.WriteLine("œil"); 

  string euro = Console.In.ReadLine();

  Console.Out.WriteLine(euro);
}

EDIT:

AS L.B. suggested you could also use Console.InputEncoding = Encoding.GetEncoding(1252).

Here is the complete example without interop (note, you could also use Windows-1252 code page for output encoding:

static void Main(string[] args)
{
  Console.InputEncoding  = Encoding.GetEncoding(1252);
  Console.OutputEncoding = Encoding.GetEncoding(1252);
  System.Console.Out.WriteLine("œil"); 

  string euro = Console.In.ReadLine();

  Console.Out.WriteLine(euro);
}

END EDIT

Hope, this helps.




回答2:


Euro sign(€):Unicode 0x20ac also UTF-8 byte sequence 0xE2 0x82 0xAC. not range of 0x80-0x9F.

char Euro = Convert.ToChar(0x20ac);
Console.WriteLine(Euro);
Console.WriteLine(Convert.ToChar(0x80));

command line input this

>csc sample.cs
>chcp 65001

The font change TrueTypeFont("Consoleas" or "Lucida Console" select) at Command Line window propaty (font tab)

>sample
€
?

(?:enclosed in square). charactor code check the font palette case 0x80-0x9F.It has not been assigned a Unicode-enabled font.



来源:https://stackoverflow.com/questions/7939643/how-do-i-read-special-characters-0x80-0x9f-from-the-windows-console-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!