Skip to content

Instantly share code, notes, and snippets.

@dranger003
Forked from tomzorz/Enable_vt100_csharp.cs
Created January 27, 2018 21:13
Show Gist options
  • Save dranger003/b63c6ab3a16b7a78604266045caee685 to your computer and use it in GitHub Desktop.
Save dranger003/b63c6ab3a16b7a78604266045caee685 to your computer and use it in GitHub Desktop.
Enable VT100 for the current console window from .NET Core
using System;
using System.Runtime.InteropServices;
namespace Vt100Test
{
public class Program
{
// ReSharper disable InconsistentNaming
private const int STD_INPUT_HANDLE = -10;
private const int STD_OUTPUT_HANDLE = -11;
private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
private const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
private const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;
// ReSharper restore InconsistentNaming
[DllImport("kernel32.dll")]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
public static void Main(string[] args)
{
var iStdIn = GetStdHandle(STD_INPUT_HANDLE);
var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleMode(iStdIn, out uint inConsoleMode))
{
Console.WriteLine("failed to get input console mode");
Console.ReadKey();
return;
}
if (!GetConsoleMode(iStdOut, out uint outConsoleMode))
{
Console.WriteLine("failed to get output console mode");
Console.ReadKey();
return;
}
inConsoleMode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
if (!SetConsoleMode(iStdIn, inConsoleMode))
{
Console.WriteLine($"failed to set input console mode, error code: {GetLastError()}");
Console.ReadKey();
return;
}
if (!SetConsoleMode(iStdOut, outConsoleMode))
{
Console.WriteLine($"failed to set output console mode, error code: {GetLastError()}");
Console.ReadKey();
return;
}
Console.Write("test");
Console.Write(new[] {(char)0x1b, '[', '1', 'B'});
Console.Write("test");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment