adding text decorations to console output

In Windows 10 build 16257 and later:

using System;
using System.Runtime.InteropServices;

class Program
{
    const int STD_OUTPUT_HANDLE = -11;
    const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);

    [DllImport("kernel32.dll")]
    static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);

    static void Main()
    {
        var handle = GetStdHandle(STD_OUTPUT_HANDLE);
        uint mode;
        GetConsoleMode(handle, out mode);
        mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        SetConsoleMode(handle, mode);

        const string UNDERLINE = "\x1B[4m";
        const string RESET = "\x1B[0m";
        Console.WriteLine("Some " + UNDERLINE + "underlined" + RESET + " text");
    }
}

Console with underlined text


The Windows console does not support ANSI escape sequences. To my knowledge, the only way to change the attributes of an output character is to call SetConsoleTextAttribute before writing the character. Or, in .NET, modify the Console.ForegroundColor or Console.BackgroundColor attributes.

It might be possible to set those properties to custom values (i.e. values not defined by ConsoleColor) with a type cast. But I don't know what good that would do you.

I don't know that I've ever seen strikethrough text on a Windows console, and it's been years since I saw underline. I suppose it's possible, but I don't know how it's done.