从Windows批处理文件中检测ANSI兼容的控制台?

时间:2016-06-27 01:36:51

标签: windows batch-file ansi-escape

Windows 10控制台主机conhost.exenative support for ANSI escape sequences,旧版本没有。如何从批处理文件中检测是否存在控制台ANSI支持?

是否可以直接从批处理文件中调用GetConsoleMode或其他Windows API调用?

1 个答案:

答案 0 :(得分:4)

您上一个问题的答案是:是的,借助PowerShell代码。此批处理文件执行您的请求:

@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...
)

我编写了这种类型的代码,在PowerShell帮助中阅读Add-Type cmdlet中的示例以及this question中接受的答案中给出的信息。