Detect ANSI-compatible console from Windows batch file?

懵懂的女人 提交于 2019-12-10 14:47:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38044810/detect-ansi-compatible-console-from-windows-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!