Windows 10 console host, conhost.exe
, has native support for ANSI escape sequences, older versions do not. How can one detect the presence or absence of console ANSI support from a batch file?
Is it possible to call GetConsoleMode
or other Windows API calls directly from a batch file?
The answer to your last question is: Yes, with the aid of PowerShell code. This Batch file do what you requested:
@echo off
setlocal
set /A STD_OUTPUT_HANDLE=-11
set /A ENABLE_PROCESSED_OUTPUT=1, ENABLE_WRAP_AT_EOL_OUTPUT=2, ENABLE_VIRTUAL_TERMINAL_PROCESSING=4
PowerShell ^
$GetStdHandle = Add-Type 'A' -PassThru -MemberDefinition ' ^
[DllImport(\"Kernel32.dll\")] ^
public static extern IntPtr GetStdHandle(int nStdHandle); ^
'; ^
$GetConsoleMode = Add-Type 'B' -PassThru -MemberDefinition ' ^
[DllImport(\"Kernel32.dll\")] ^
public static extern bool GetConsoleMode(IntPtr hWnd, ref UInt32 lpMode); ^
'; ^
$StdoutHandle = $GetStdHandle::GetStdHandle(%STD_OUTPUT_HANDLE%); ^
$ConsoleMode = New-Object -TypeName UInt32; ^
$null = $GetConsoleMode::GetConsoleMode($StdoutHandle,[ref]$ConsoleMode); ^
Set-Content ConsoleMode.txt $ConsoleMode ^
%End PowerShell%
set /P "ConsoleMode=" < ConsoleMode.txt
set /A "AnsiCompatible=ConsoleMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING"
if %AnsiCompatible% neq 0 (
echo The console is Ansi-compatible!
) else (
echo Ansi codes not supported...
)
I wrote this type of code reading the examples at the PowerShell help on Add-Type cmdlet and the info given in the accepted answer at this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With