Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect ANSI-compatible console from Windows batch file?

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?

like image 476
jwfearn Avatar asked Jun 27 '16 01:06

jwfearn


1 Answers

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.

like image 182
Aacini Avatar answered Nov 15 '22 10:11

Aacini