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

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

本文介绍了从Windows批处理文件中检测ANSI兼容控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows 10控制台主机 conhost.exe 具有,而较早的版本则不支持。如何从批处理文件中检测是否存在控制台ANSI支持?

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?

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

Is it possible to call GetConsoleMode or other Windows API calls directly from a batch file?

推荐答案

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

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

我编写了此类代码在Add-Type cmdlet的PowerShell帮助中阅读示例,并在。

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.

这篇关于从Windows批处理文件中检测ANSI兼容控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:42