是否可以使用批处理编程在命令提示符下输出当前颜色代码?

问题描述 投票:4回答:4

我正在使用批处理编程为我的一个朋友制作一个教程程序。我想知道是否有可能在显示当前颜色代码的文件中写入代码。

示例是当前将颜色设置为0A,并且我想在行上显示:

echo The color is currently set to 0A

我希望我的文件读取设置为的代码并显示它,以帮助他们记住所做的更改,因为这是命令提示符/批处理中颜色代码的示例程序。

谢谢您的帮助!

batch-file command-prompt
4个回答
4
投票

很容易制作自己的命令来执行此操作。将下面的两个文本文件都复制到同一文件夹中的GetConsoleColour.batGetConsoleColour.vb中。双击批处理文件,它将创建GetConsoleColour.exe

PS 颜色的拼写符合我的文化。在撰写本文时,我认为在编程中通常不需要使用美国拼写。

请参见https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo

GetConsoleColour.exe以十六进制打印当前控制台颜色,并且返回带有值的错误级别

使用

C:\PathToFile\GetConsoleColour

我这里有一个程序,可以逐行设置文本颜色。这是唯一适用于所有Windows计算机的技术。

Command Prompt Scripting: Problem with multiple colors in a batch file

还有一个类似的程序,该控制台窗口中有多少个进程-ListConsole.exe列出当前控制台中的进程,并返回一个错误级别,指出有多少个进程。 https://winsourcecode.blogspot.com/2019/05/listconsoleexe-list-processes-in.html


REM GetConsoleColour.bat
REM This file compiles GetConsoleColour.vb to GetConsoleColour.exe
REM GetConsoleColour.exe prints the current console colour and returns an errorlevel with the value
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\GetConsoleColour.exe" "%~dp0\GetConsoleColour.vb" 
pause

注意:这里只有4行代码。剩下的只是程序执行这4行所需的信息。在大型程序中,它们将被隐藏在单独的文件中。

'GetConsoleColour.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication 

Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Declare Function GetConsoleScreenBufferInfo Lib "kernel32" (ByVal hConsoleOutput As Integer, ByRef lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Integer
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

 <StructLayout(LayoutKind.Sequential)> _
Public Structure COORD
    Public x As Short
    Public y As Short
End Structure

 <StructLayout(LayoutKind.Sequential)> _
Public Structure SMALL_RECT
    Public Left As Short
    Public Top As Short
    Public Right As Short
    Public Bottom As Short
End Structure

 <StructLayout(LayoutKind.Sequential)> _
Public Structure CONSOLE_SCREEN_BUFFER_INFO
    Public dwSize As COORD
    Public dwCursorPosition As COORD
    Public wAttributes As Integer
    Public srWindow As SMALL_RECT
    Public dwMaximumWindowSize As COORD
End Structure 


Sub Main()
    Dim hOut as IntPtr
    Dim Ret as Integer
    Dim CSBI as Console_Screen_Buffer_Info
    hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
    Ret = GetConsoleScreenBufferInfo(hOut, CSBI)
    Console.Writeline(Hex(CSBI.wAttributes))
    Environment.ExitCode = CSBI.wAttributes
End Sub
End Module

1
投票

通过做出妥协并使用setlocal EnableDelayedExpansion,可以使用以下方法:

@ECHO OFF

Setlocal enableDelayedExpansion

Set "Color=Color 02" && !color!

ECHO Color is currently %color%

pause

此方法的缺点是更改控制台颜色成为2步过程(取决于您显示信息的方式)。


0
投票

正如在另一个答案中已经指出的,您可以使用中的向您显示当前的颜色顺序:

@(For /F %%# In ('^""%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" -NoP "$Console=(Get-Host).UI.RawUI;Switch($Console.BackgroundColor,$Console.ForegroundColor){'Black'{'0'}'Dark Blue'{'1'}'Dark Green'{'2'}'Dark Cyan'{'3'}'Dark Red'{'4'}'Dark Magenta'{'5'}'Dark Yellow'{'6'}'Gray'{'7'}'Dark Gray'{'8'}'Blue'{'9'}'Green'{'A'}'Cyan'{'B'}'Red'{'C'}'Magenta'{'D'}'Yellow'{'E'}'White'{'F'}}" 2^>NUL^"')Do @Set/P=%%#<NUL)&Echo(&Pause

您也应该可以从进行此操作:

(For /F %# In ('^""%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" -NoP "$Console=(Get-Host).UI.RawUI;Switch($Console.BackgroundColor,$Console.ForegroundColor){'Black'{'0'}'Dark Blue'{'1'}'Dark Green'{'2'}'Dark Cyan'{'3'}'Dark Red'{'4'}'Dark Magenta'{'5'}'Dark Yellow'{'6'}'Gray'{'7'}'Dark Gray'{'8'}'Blue'{'9'}'Green'{'A'}'Cyan'{'B'}'Red'{'C'}'Magenta'{'D'}'Yellow'{'E'}'White'{'F'}}" 2^>NUL^"')Do @Set/P=%#<NUL)&Echo(

0
投票

enter image description here


  • 更新:在运行时生成C#.exe

此bat文件将在运行时生成一个fFB.cs文件,并将生成可执行文件fCB.exe以使用ConsoleColor Enum执行它们


@echo off && setlocal EnableDelayedExpansion 

set "_color="0 Black","1 DarkBlue","2 DarkGreen","3 DarkCyan","4 DarkRed","
@set "_color=!_color!"5 DarkMagenta","6 DarkYellow","7 Gray","8 DarkGray","
      set "_color=!_color!"9 Blue","A Green","B Cyan","C Red","D Magenta","
      set "_color=!_color!"E Yellow","F White"" && cd/d "%~dp0" && title %0

for %%D in (.exe,.cs) do if exist "%temp%\cFB%%~D" (2>nul >nul del /q /f "%temp%\cFB%%~D")
set "_csc=%windir%\Microsoft.NET"&& set "_where=%__appdir__%where.exe" && set "_cs=cFB.cs"
set "_arg=/t:exe /out:"%tmp%\!_cs:~,-3!.exe" "%tmp%\!_cs!" /platform:x86 /unsafe+ /w:0 /o"

set "_c=!_where! /r "!_csc!" "csc.exe" "&& set "_#=%temp%\!_cs!" && cmd/v/c echo=&>"!_#!"^
     (
     echo/ using System; namespace cFB ^{class Program ^{public static void Main(^)^{
     echo/ ConsoleColor currentForeground=Console.ForegroundColor;
     echo/ ConsoleColor currentBackground=Console.BackgroundColor;
     echo/ Console.WriteLine("{0}\n{1}",Console.ForegroundColor,Console.BackgroundColor^);^}^}^}
     ) && (pushd "%temp%" & goto :run)||echo=Well, something is really wrong here^!! & goto :Err

:run
for /f tokens^=* %%i in ('!_c!^|find "k\v2"')do "%%~i" /nologo !_arg!&& if exist "!_#:~0,-3!.exe" (
for /f ^delims^=^ ^eol^= %%r in ('"!_#:~0,-3!.exe"')do set "_Hex=%%r") else (popd && cls 2>nul && (
echo=File: "!_#:~0,-3!.exe" not found, something is really wrong here^^!!& timeout -1& goto :Err) )

for /f tokens^=^*^delims^= %%I in ('"!_#:~0,-3!.exe"')do for %%# in (!_color!)do set "_h=%%~#" && (
if "%%~I"=="!_h:~2!" if not "!_fb!"=="!_h:~0,l!" (set "_fb=!_h:~0,1!!_fb!"&&set "_l= !_h:~2!!_l!"))

set "_l=!_l:~1!" && for %%D in (.exe,.cs) do if exist "%temp%\cFB%%~D" >nul del /q "%temp%\cFB%%~D" 
cmd /v /c echo The color is currently set to: !_fb! (!_l: =/!^) && endlocal && exit /b || goto :EOF

:Err
endlocal & exit /b || goto :EOF

这是C#代码,没有转义:

using System;
namespace CBF 
{ 
   class Program 
   {
      public static void Main()
      {
         ConsoleColor currentBackground=Console.BackgroundColor;
         ConsoleColor currentForeground=Console.ForegroundColor;
         Console.WriteLine("{0}\n{1}",Console.ForegroundColor,Console.BackgroundColor);
      }
   }
}

  • Bat Run C#命令输出:
The color is currently set to: 0A (Black/Green)

  • 用于生成可执行文件的命令行:
"C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe" /nologo /t:exe /out:"%temp%\cFB.exe" "%temp%\cFB.cs" /platform:x86 /w:0 /o


您也可以尝试在$Host.UI.RawUI

中使用寻求帮助。
@echo off && setlocal EnableDelayedExpansion 

set "_color="0 Black","1 DarkBlue","2 DarkGreen","3 DarkCyan","4 DarkRed","
@set "_color=!_color!"5 DarkMagenta","6 DarkYellow","7 Gray","8 DarkGray","
      set "_color=!_color!"9 Blue","A Green","B Cyan","C Red","D Magenta","
      set "_color=!_color!"E Yellow","F White""&& cd/d "%~dp0" && title %~0

for /f tokens^=2^delims^=^:^  %%I in ('powershell -nOp $Host.UI.RawUI^|find "Color"')do (
for %%# in (!_color!)do set "_Hex=%%~#"&& for /f %%a in ('cd')do if "%%~I"=="!_Hex:~2!" (
if not "!_FB!"=="!_Hex:~1,1!" ( set "_FB=!_Hex:~0,1!!_FB!" && set "_L= !_Hex:~2!!_L!" )))

set "_L=!_L:~1!"&& cmd/v/c echo The color is currently set to !_FB! (!_L: =/!^)&&endlocal


  • 蝙蝠文件输出:
    The color is currently set to A3 (Green/DarkCyan)
    

rem :: just type :: 
powershell -nop -c "$Host.UI.RawUI"|find "Color"

  • $ Host.UI.RawUI输出:
    ForegroundColor       : White
    BackgroundColor       : Blue
    

    • $ Host.UI.RawUI完整输出:
ForegroundColor       : White
BackgroundColor       : Blue
CursorPosition        : 0,108
WindowPosition        : 0,90
CursorSize            : 25
BufferSize            : 99,770
WindowSize            : 89,48
MaxWindowSize         : 99,50
MaxPhysicalWindowSize : 174,50
KeyAvailable          : False
WindowTitle           : Q59449889v2.cmd - powershell  $Host.UI.RawUI

对不起,我的限定English


© www.soinside.com 2019 - 2024. All rights reserved.