56 lines
1.7 KiB
C#
56 lines
1.7 KiB
C#
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
|
|
namespace MAF1.Utils;
|
|
|
|
public static class WindowsConsole
|
|
{
|
|
private const uint Utf8CodePage = 65001;
|
|
private const int StdOutputHandle = -11;
|
|
private const uint EnableVirtualTerminalProcessing = 0x0004;
|
|
|
|
public static void EnableUtf8()
|
|
{
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
|
|
Console.InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
|
|
return;
|
|
}
|
|
|
|
SetConsoleOutputCP(Utf8CodePage);
|
|
SetConsoleCP(Utf8CodePage);
|
|
|
|
UTF8Encoding utf8 = new(encoderShouldEmitUTF8Identifier: false);
|
|
Console.OutputEncoding = utf8;
|
|
Console.InputEncoding = utf8;
|
|
|
|
nint stdout = GetStdHandle(StdOutputHandle);
|
|
if (stdout != nint.Zero && GetConsoleMode(stdout, out uint mode))
|
|
{
|
|
SetConsoleMode(stdout, mode | EnableVirtualTerminalProcessing);
|
|
}
|
|
|
|
StreamWriter writer = new(Console.OpenStandardOutput(), utf8)
|
|
{
|
|
AutoFlush = true,
|
|
};
|
|
Console.SetOut(writer);
|
|
}
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool SetConsoleOutputCP(uint wCodePageID);
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool SetConsoleCP(uint wCodePageID);
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern nint GetStdHandle(int nStdHandle);
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool GetConsoleMode(nint hConsoleHandle, out uint lpMode);
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool SetConsoleMode(nint hConsoleHandle, uint dwMode);
|
|
}
|