-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsoleUtils.cs
executable file
·53 lines (42 loc) · 1.4 KB
/
ConsoleUtils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Scripting
{
public class ConsoleUtils
{
private enum StdHandle { Stdin = -10, Stdout = -11 };
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(StdHandle std);
[DllImport("kernel32.dll")]
static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
public static void EnableANSI()
{
try
{
EnableANSIInternal();
}
catch
{
// ansi already enabled, or non-conventional console
}
}
private static void EnableANSIInternal()
{
const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
IntPtr outConsoleHandle = GetStdHandle(StdHandle.Stdout);
if (!GetConsoleMode(outConsoleHandle, out uint outConsoleMode))
Fail();
outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(outConsoleHandle, outConsoleMode))
Fail();
}
private static void Fail()
{
// The exception will include the last win32 error
throw new Win32Exception();
}
}
}