Hoe kan ik meerdere kleuren in een Windows-batchbestand hebben?

Ik vroeg me af of het mogelijk is om tekst in verschillende kleuren op dezelfde regel in een Windows-batchbestand te hebben, bijvoorbeeld als er staat

echo hi world

Ik wil dat ‘hoi’ één kleur is en ‘wereld’ een andere kleur. Misschien kan ik het COLOR-commando als variabele instellen:

set color1= color 2
set color9= color A

en zet ze vervolgens beide op dezelfde lijn samen met

echo hi world

maar ik weet niet hoe ik dat zou moeten doen.


Antwoord 1, autoriteit 100%

Je kunt meerkleurige outputs maken zonder externe programma’s.

@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :eof
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof

Het gebruikt de kleurfunctie van de opdracht findstr.

Findstr kan worden geconfigureerd om regelnummers of bestandsnamen in een gedefinieerde kleur uit te voeren.
Dus maak ik eerst een bestand met de tekst als bestandsnaam, en de inhoud is een enkel <backspace>teken (ASCII 8).
Dan zoek ik alle niet-lege regels in het bestand en in nul, zodat de bestandsnaam wordt uitgevoerd in de juiste kleur met een dubbele punt, maar de dubbele punt wordt onmiddellijk verwijderd door de <backspace>.

BEWERK: Een jaar later … zijn alle tekens geldig

@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
exit /b
:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b

Dit gebruikt de regel voor geldige pad-/bestandsnamen.
Als een \..\in het pad staat, wordt het voorvoegsel volledig verwijderd en is het niet nodig dat dit element alleen geldige bestandsnaamtekens bevat.


Antwoord 2, autoriteit 60%

jeb’s aangepaste antwoord komt in de buurt van het oplossen van alle problemen. Maar het heeft problemen met de volgende strings:

"a\b\"
"a/b/"
"\"
"/"
"."
".."
"c:"

Ik heb zijn techniek aangepast tot iets waarvan ik denk dat het echt elke reeks afdrukbare karakters aankan, behalve lengtebeperkingen.

Andere verbeteringen:

  • Gebruikt de %TEMP% locatie voor het tijdelijke bestand, dus geen schrijftoegang meer nodig tot de huidige map.

  • Twee varianten gemaakt, de ene neemt een tekenreeks letterlijk, de andere de naam van een variabele die de tekenreeks bevat. De variabele versie is over het algemeen minder handig, maar elimineert enkele problemen met het ontsnappen van speciale tekens.

  • De optie /n toegevoegd als een optionele derde parameter om een ​​nieuwe regel aan het einde van de uitvoer toe te voegen.

Backspace werkt niet over een regeleinde, dus de techniek kan problemen hebben als de regel terugloopt. Het afdrukken van een string met een lengte tussen 74 en 79 zal bijvoorbeeld niet goed werken als de console een lijnbreedte van 80 heeft.

@echo off
setlocal
call :initColorPrint
call :colorPrint 0a "a"
call :colorPrint 0b "b"
set "txt=^" & call :colorPrintVar 0c txt
call :colorPrint 0d "<"
call :colorPrint 0e ">"
call :colorPrint 0f "&"
call :colorPrint 1a "|"
call :colorPrint 1b " "
call :colorPrint 1c "%%%%"
call :colorPrint 1d ^"""
call :colorPrint 1e "*"
call :colorPrint 1f "?"
call :colorPrint 2a "!"
call :colorPrint 2b "."
call :colorPrint 2c ".."
call :colorPrint 2d "/"
call :colorPrint 2e "\"
call :colorPrint 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :colorPrintVar 74 complex /n
call :cleanupColorPrint
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color  Str  [/n]
setlocal
set "str=%~2"
call :colorPrintVar %1 str %3
exit /b
:colorPrintVar  Color  StrVar  [/n]
if not defined %~2 exit /b
setlocal enableDelayedExpansion
set "str=a%DEL%!%~2:\=a%DEL%\..\%DEL%%DEL%%DEL%!"
set "str=!str:/=a%DEL%/..\%DEL%%DEL%%DEL%!"
set "str=!str:"=\"!"
pushd "%temp%"
findstr /p /A:%1 "." "!str!\..\x" nul
if /i "%~3"=="/n" echo(
exit /b
:initColorPrint
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do set "DEL=%%a"
<nul >"%temp%\x" set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%.%DEL%"
exit /b
:cleanupColorPrint
del "%temp%\x"
exit /b

UPDATE 27-11-2012

Deze methode mislukt op XP omdat FINDSTR backspace weergeeft als een punt op het scherm. het oorspronkelijke antwoord van jeb werkt op XP, zij het met de reeds vermelde beperkingen

UPDATE 14-12-2012

Er is veel ontwikkelingsactiviteit geweest op DosTipsen SS64. Het blijkt dat FINDSTR ook bestandsnamen corrumpeert die uitgebreide ASCII bevatten als ze op de opdrachtregel worden opgegeven. Ik heb mijn FINDSTR Q&Abijgewerkt.

Hieronder staat een versie die werkt op XP en ALLE tekens van één byte ondersteunt, behalve 0x00 (nul), 0x0A (linefeed) en 0x0D (carriage return). Als u echter op XP draait, worden de meeste controletekens weergegeven als stippen. Dit is een inherent kenmerk van FINDSTR op XP dat niet kan worden vermeden.

Helaas vertraagt ​​het toevoegen van ondersteuning voor XP en voor uitgebreide ASCII-tekens de routine 🙁

Voor de lol heb ik wat ASCII-kleuren in kleur gepakt van joan stark’s ASCII Art Galleryen aangepast voor gebruik met ColorPrint. Ik heb een :c-ingangspunt toegevoegd, alleen voor steno, en om een ​​probleem met letterlijke aanhalingstekens op te lossen.

@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E "                ,      .-;" /n
call :c 0E "             ,  |\    / /  __," /n
call :c 0E "             |\ '.`-.|  |.'.-'" /n
call :c 0E "              \`'-:  `; : /" /n
call :c 0E "               `-._'.  \'|" /n
call :c 0E "              ,_.-=` ` `  ~,_" /n
call :c 0E "               '--,.    "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E "                 /     "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E "                 |      "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E "                 /          "&call :c 06 "\_,\|" /n
call :c 0E "                 |          (" /n
call :c 0E "             "&call :c 0c "__ "&call :c 0E "/ '          \" /n
call :c 02 "     /\_    "&call :c 0c "/,'`"&call :c 0E "|     '   "&call :c 0c ".-~!q!~~-." /n
call :c 02 "     |`.\_ "&call :c 0c "|   "&call :c 0E "/  ' ,    "&call :c 0c "/        \" /n
call :c 02 "   _/  `, \"&call :c 0c "|  "&call :c 0E "; ,     . "&call :c 0c "|  ,  '  . |" /n
call :c 02 "   \   `,  "&call :c 0c "|  "&call :c 0E "|  ,  ,   "&call :c 0c "|  :  ;  : |" /n
call :c 02 "   _\  `,  "&call :c 0c "\  "&call :c 0E "|.     ,  "&call :c 0c "|  |  |  | |" /n
call :c 02 "   \`  `.   "&call :c 0c "\ "&call :c 0E "|   '     "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 "   _\   `,   "&call :c 0A "`"&call :c 0E "\  '  . ' "&call :c 0A "| |  | |  |           "&call :c 02 "__" /n
call :c 02 "   \     `,   "&call :c 0E "| ,  '    "&call :c 0A "|_/'-|_\_/     "&call :c 02 "__ ,-;` /" /n
call :c 02 "    \    `,    "&call :c 0E "\ .  , ' .| | | | |   "&call :c 02 "_/' ` _=`|" /n
call :c 02 "     `\    `,   "&call :c 0E "\     ,  | | | | |"&call :c 02 "_/'   .=!q!  /" /n
call :c 02 "     \`     `,   "&call :c 0E "`\      \/|,| ;"&call :c 02 "/'   .=!q!    |" /n
call :c 02 "      \      `,    "&call :c 0E "`\' ,  | ; "&call :c 02 "/'    =!q!    _/" /n
call :c 02 "       `\     `,  "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/'    =!q!     /" /n
call :c 02 "    jgs _`\    ;"&call :c 05 "_{  '   ; "&call :c 02 "/'    =!q!      /" /n
call :c 02 "       _\`-/__"&call :c 05 ".~  `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q!     _,/" /n
call :c 02 "    __\      "&call :c 05 "{   '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 "    _/" /n
call :c 02 "    \    .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..'  "&call :c 02 "__/" /n
call :c 02 "   _/  .!q!    "&call :c 05 "{  -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 "  /  .!q!    _/'"&call :c 05 "`--; ;  `.  ;" /n
call :c 02 "   .=!q!  _/'      "&call :c 05 "`-..__,-'" /n
call :c 02 "    __/'" /n
echo(
exit /b
:c
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color  Str  [/n]
setlocal
set "s=%~2"
call :colorPrintVar %1 s %3
exit /b
:colorPrintVar  Color  StrVar  [/n]
if not defined DEL call :initColorPrint
setlocal enableDelayedExpansion
pushd .
':
cd \
set "s=!%~2!"
:: The single blank line within the following IN() clause is critical - DO NOT REMOVE
for %%n in (^"^
^") do (
  set "s=!s:\=%%~n\%%~n!"
  set "s=!s:/=%%~n/%%~n!"
  set "s=!s::=%%~n:%%~n!"
)
for /f delims^=^ eol^= %%s in ("!s!") do (
  if "!" equ "" setlocal disableDelayedExpansion
  if %%s==\ (
    findstr /a:%~1 "." "\'" nul
    <nul set /p "=%DEL%%DEL%%DEL%"
  ) else if %%s==/ (
    findstr /a:%~1 "." "/.\'" nul
    <nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%"
  ) else (
    >colorPrint.txt (echo %%s\..\')
    findstr /a:%~1 /f:colorPrint.txt "."
    <nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
  )
)
if /i "%~3"=="/n" echo(
popd
exit /b
:initColorPrint
for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "DEL=%%A %%A"
<nul >"%temp%\'" set /p "=."
subst ': "%temp%" >nul
exit /b
:cleanupColorPrint
2>nul del "%temp%\'"
2>nul del "%temp%\colorPrint.txt"
>nul subst ': /d
exit /b

Antwoord 3, autoriteit 36%

Eigenlijk kan dit worden gedaan zonder een tijdelijk bestand aan te maken.
De methode beschreven door jeb en dbenham werkt zelfs met een doelbestand dat geen backspaces bevat. Het kritieke punt is dat de regel die wordt herkend door findstr.exe niet mag eindigen met een CRLF.
Het voor de hand liggende tekstbestand dat moet worden gescand met een regel die niet eindigt met een CRLF, is dus de batch zelf die wordt aangeroepen, op voorwaarde dat we deze met zo’n regel beëindigen!
Hier is een bijgewerkt voorbeeldscript dat op deze manier werkt…

Veranderingen ten opzichte van het vorige voorbeeld:

  • Gebruikt een enkel streepje op de laatste regel als de doorzoekbare tekenreeks. (Moet kort zijn en nergens anders op deze manier in de batch voorkomen.)
  • De naam van routines en variabelen is iets meer objectgericht 🙂
  • Eén oproepniveau verwijderd om de prestaties iets te verbeteren.
  • Opmerkingen toegevoegd (beginnend met :# om meer op de meeste andere scripttalen te lijken.)

@echo off
setlocal
call :Echo.Color.Init
goto main
:Echo.Color %1=Color %2=Str [%3=/n]
setlocal enableDelayedExpansion
set "str=%~2"
:Echo.Color.2
:# Replace path separators in the string, so that the final path still refers to the current path.
set "str=a%ECHO.DEL%!str:\=a%ECHO.DEL%\..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!"
set "str=!str:/=a%ECHO.DEL%/..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!"
set "str=!str:"=\"!"
:# Go to the script directory and search for the trailing -
pushd "%ECHO.DIR%"
findstr /p /r /a:%~1 "^^-" "!str!\..\!ECHO.FILE!" nul
popd
:# Remove the name of this script from the output. (Dependant on its length.)
for /l %%n in (1,1,12) do if not "!ECHO.FILE:~%%n!"=="" <nul set /p "=%ECHO.DEL%"
:# Remove the other unwanted characters "\..\: -"
<nul set /p "=%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%"
:# Append the optional CRLF
if not "%~3"=="" echo.
endlocal & goto :eof
:Echo.Color.Var %1=Color %2=StrVar [%3=/n]
if not defined %~2 goto :eof
setlocal enableDelayedExpansion
set "str=!%~2!"
goto :Echo.Color.2
:Echo.Color.Init
set "ECHO.COLOR=call :Echo.Color"
set "ECHO.DIR=%~dp0"
set "ECHO.FILE=%~nx0"
set "ECHO.FULL=%ECHO.DIR%%ECHO.FILE%"
:# Use prompt to store a backspace into a variable. (Actually backspace+space+backspace)
for /F "tokens=1 delims=#" %%a in ('"prompt #$H# & echo on & for %%b in (1) do rem"') do set "ECHO.DEL=%%a"
goto :eof
:main
call :Echo.Color 0a "a"
call :Echo.Color 0b "b"
set "txt=^" & call :Echo.Color.Var 0c txt
call :Echo.Color 0d "<"
call :Echo.Color 0e ">"
call :Echo.Color 0f "&"
call :Echo.Color 1a "|"
call :Echo.Color 1b " "
call :Echo.Color 1c "%%%%"
call :Echo.Color 1d ^"""
call :Echo.Color 1e "*"
call :Echo.Color 1f "?"
:# call :Echo.Color 2a "!"
call :Echo.Color 2b "."
call :Echo.Color 2c ".."
call :Echo.Color 2d "/"
call :Echo.Color 2e "\"
call :Echo.Color 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :Echo.Color.Var 74 complex /n
exit /b
:# The following line must be last and not end by a CRLF.
-

PS. Ik heb een probleem met de uitvoer van de ! teken dat u in het vorige voorbeeld niet had. (Of je had in ieder geval niet dezelfde symptomen.) Te onderzoeken.


Antwoord 4, autoriteit 20%

Als je een moderne Windows hebt (waarop powershell is geïnstalleerd), kan het volgende ook goed werken

call :PrintBright Something Something
  (do actual batch stuff here)
call :PrintBright Done!
goto :eof
:PrintBright
powershell -Command Write-Host "%*" -foreground "White"

Pas de kleur naar eigen inzicht aan.


Antwoord 5, autoriteit 9%

Combinatie van dbenham’s bird en syntaxismet skrebbel’s powershell write-hostmethode, het lijkt erop dat powershell complexe kunst sneller kan renderen dan de pure batchmethode van dbenham (nou ja, nadat powershell in ieder geval eenmaal is geprimed). Minimale massage van de snaren is nodig, hoewel ik dit met niets anders dan de vogel heb getest. Als je bijvoorbeeld een felgroen einde-van-transmissie-teken wilt, heb je misschien pech. 🙂

Voor deze methode is echo-out nodig naar een tijdelijk bestand, simpelweg omdat het aanroepen van powershell voor elke call :ceen eeuwigheid duurt, en het is veel sneller om de uitvoer in de wachtrij te zetten voor één powershell-aanroep. Maar het heeft wel het voordeel van eenvoud en efficiëntie.

@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E "                ,      .-;" /n
call :c 0E "             ,  |\    / /  __," /n
call :c 0E "             |\ '.`-.|  |.'.-'" /n
call :c 0E "              \`'-:  `; : /" /n
call :c 0E "               `-._'.  \'|" /n
call :c 0E "              ,_.-=` ` `  ~,_" /n
call :c 0E "               '--,.    "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E "                 /     "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E "                 |      "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E "                 /          "&call :c 06 "\_,\|" /n
call :c 0E "                 |          (" /n
call :c 0E "             "&call :c 0c "__ "&call :c 0E "/ '          \" /n
call :c 02 "     /\_    "&call :c 0c "/,'`"&call :c 0E "|     '   "&call :c 0c ".-~!q!~~-." /n
call :c 02 "     |`.\_ "&call :c 0c "|   "&call :c 0E "/  ' ,    "&call :c 0c "/        \" /n
call :c 02 "   _/  `, \"&call :c 0c "|  "&call :c 0E "; ,     . "&call :c 0c "|  ,  '  . |" /n
call :c 02 "   \   `,  "&call :c 0c "|  "&call :c 0E "|  ,  ,   "&call :c 0c "|  :  ;  : |" /n
call :c 02 "   _\  `,  "&call :c 0c "\  "&call :c 0E "|.     ,  "&call :c 0c "|  |  |  | |" /n
call :c 02 "   \`  `.   "&call :c 0c "\ "&call :c 0E "|   '     "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 "   _\   `,   "&call :c 0A "`"&call :c 0E "\  '  . ' "&call :c 0A "| |  | |  |           "&call :c 02 "__" /n
call :c 02 "   \     `,   "&call :c 0E "| ,  '    "&call :c 0A "|_/'-|_\_/     "&call :c 02 "__ ,-;` /" /n
call :c 02 "    \    `,    "&call :c 0E "\ .  , ' .| | | | |   "&call :c 02 "_/' ` _=`|" /n
call :c 02 "     `\    `,   "&call :c 0E "\     ,  | | | | |"&call :c 02 "_/'   .=!q!  /" /n
call :c 02 "     \`     `,   "&call :c 0E "`\      \/|,| ;"&call :c 02 "/'   .=!q!    |" /n
call :c 02 "      \      `,    "&call :c 0E "`\' ,  | ; "&call :c 02 "/'    =!q!    _/" /n
call :c 02 "       `\     `,  "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/'    =!q!     /" /n
call :c 02 "    jgs _`\    ;"&call :c 05 "_{  '   ; "&call :c 02 "/'    =!q!      /" /n
call :c 02 "       _\`-/__"&call :c 05 ".~  `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q!     _,/" /n
call :c 02 "    __\      "&call :c 05 "{   '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 "    _/" /n
call :c 02 "    \    .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..'  "&call :c 02 "__/" /n
call :c 02 "   _/  .!q!    "&call :c 05 "{  -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 "  /  .!q!    _/'"&call :c 05 "`--; ;  `.  ;" /n
call :c 02 "   .=!q!  _/'      "&call :c 05 "`-..__,-'" /n
call :c 02 "    __/'" /n
if exist "%temp%\color.psm1" (
    powershell -command "&{set-executionpolicy remotesigned; Import-Module '%temp%\color.psm1'}"
    del "%temp%\color.psm1"
)
echo(
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:c <color pair> <string> </n>
setlocal enabledelayedexpansion
set "colors=0-black;1-darkblue;2-darkgreen;3-darkcyan;4-darkred;5-darkmagenta;6-darkyellow;7-gray;8-darkgray;9-blue;a-green;b-cyan;c-red;d-magenta;e-yellow;f-white"
set "p=%~1"
set "bg=!colors:*%p:~0,1%-=!"
set bg=%bg:;=&rem.%
set "fg=!colors:*%p:~-1%-=!"
set fg=%fg:;=&rem.%
if not "%~3"=="/n" set "br=-nonewline"
set "str=%~2" & set "str=!str:'=''!"
>>"%temp%\color.psm1" echo write-host '!str!' -foregroundcolor '%fg%' -backgroundcolor '%bg%' %br%
endlocal

Resultaat:

Voer de afbeeldingsomschrijving hier in


Antwoord 6, autoriteit 5%

Ja, het is mogelijk met cmdcolor:

echo \033[32mhi \033[92mworld

hizal donkergroen zijn, en world– lichtgroen.


Antwoord 7, autoriteit 4%

Windows 10 ((Versie 1511, build 10586, release 2015-11-10)) ondersteunt ANSI-kleuren.
U kunt de escape-toets gebruiken om de kleurcodes te activeren.

In de opdrachtprompt:

echo ^[[32m HI ^[[0m

echo Ctrl+[[32m HICtrl+[[0mEnter

Als je een teksteditor gebruikt, kun je ALT-sleutelcodes gebruiken.
De ESC-sleutelcode kan worden gemaakt met behulp van ALTen NUMPAD-nummers: Alt+027

[32m  HI  [0m

Antwoord 8, autoriteit 3%

Verschillende methoden worden behandeld in
“51} Hoe kan ik regels in verschillende kleuren in NT-scripts herhalen?”
http://www.netikka.net/tsneti/info/tscmd051.htm

Een van de alternatieven: als u aan QBASIC kunt komen, is het gebruik van kleuren relatief eenvoudig:

 @echo off & setlocal enableextensions
  for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
  set skip=
  findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
  qbasic /run %temp_%\tmp$$$.bas
  for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
  endlocal & goto :EOF
  ::
  CLS 'QB
  COLOR 14,0 'QB
  PRINT "A simple "; 'QB
  COLOR 13,0 'QB
  PRINT "color "; 'QB
  COLOR 14,0 'QB
  PRINT "demonstration" 'QB
  PRINT "By Prof. (emer.) Timo Salmi" 'QB
  PRINT 'QB
  FOR j = 0 TO 7 'QB
    FOR i = 0 TO 15 'QB
      COLOR i, j 'QB
      PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
      COLOR 1, 0 'QB
      PRINT " "; 'QB
    NEXT i 'QB
    PRINT 'QB
  NEXT j 'QB
  SYSTEM 'QB

Antwoord 9

Je moet chgcolor.zip downloaden van
http://www.mailsend-online .com/blog/setting-text-color-in-a-batch-file.html
en download ook echoj.zip van
www.mailsend-online.com/blog/?p=41
Ze staan ​​allebei onderaan de pagina.
Pak beide mappen uit naar het bureaublad
en kopieer de uitvoerbare bestanden (.exe-bestanden) vanuit de uitgepakte mappen naar de map C:\Windows. Hierdoor kunnen ze worden uitgevoerd vanaf de opdrachtregel.
Open Kladblok en kopieer het volgende erin:

@echo uit

chgcolor 03

echoj “hallo”

chgcolor 0d

echoj “wereld”

chgcolor 07

echoj $0a

Sla het bestand op het bureaublad op als hi.bat. Open nu de opdrachtprompt en navigeer naar uw bureaubladmap en typ “hi.bat” zonder de aanhalingstekens. Dat zou u op weg moeten helpen. Zorg ervoor dat u beide webpagina’s leest om een ​​volledige zelfstudie te krijgen.


Antwoord 10

Als je console ANSI-kleurcodes ondersteunt (bijv. ConEmu, Clinkof ANSICON) kunt u doe dit:

SET    GRAY=%ESC%[0m
SET     RED=%ESC%[1;31m
SET   GREEN=%ESC%[1;32m
SET  ORANGE=%ESC%[0;33m
SET    BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET    CYAN=%ESC%[1;36m
SET   WHITE=%ESC%[1;37m

waar de ESC-variabele ASCII-teken 27 bevat.

Ik heb een manier gevonden om de ESC-variabele hier in te vullen: http:/ /www.dostips.com/forum/viewtopic.php?p=6827#p6827
en met behulp van tasklistis het mogelijk om te testen welke DLL’s in een proces worden geladen.

Het volgende script haalt de proces-ID op van de cmd.exe waarin het script wordt uitgevoerd. Controleert of het een dll heeft die ANSI-ondersteuning toevoegt, en stelt vervolgens kleurvariabelen in om escape-reeksen te bevatten of leeg te zijn, afhankelijk van of kleur wordt ondersteund of niet.

@echo off
call :INIT_COLORS
echo %RED%RED %GREEN%GREEN %ORANGE%ORANGE %BLUE%BLUE %MAGENTA%MAGENTA %CYAN%CYAN %WHITE%WHITE %GRAY%GRAY
:: pause if double clicked on instead of run from command line.
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1
@rem ECHO %CMDCMDLINE% %COMSPEC% %interactive%
IF "%interactive%"=="1" PAUSE
EXIT /B 0
Goto :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
: SUBROUTINES                                                          :
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::
:INIT_COLORS
::::::::::::::::::::::::::::::::
call :supportsANSI
if ERRORLEVEL 1 (
  SET GREEN=
  SET RED=
  SET GRAY=
  SET WHITE=
  SET ORANGE=
  SET CYAN=
) ELSE (
  :: If you can, insert ASCII CHAR 27 after equals and remove BL.String.CreateDEL_ESC routine
  set "ESC="
  :: use this if can't type ESC CHAR, it's more verbose, but you can copy and paste it
  call :BL.String.CreateDEL_ESC
  SET    GRAY=%ESC%[0m
  SET     RED=%ESC%[1;31m
  SET   GREEN=%ESC%[1;32m
  SET  ORANGE=%ESC%[0;33m
  SET    BLUE=%ESC%[0;34m
  SET MAGENTA=%ESC%[0;35m
  SET    CYAN=%ESC%[1;36m
  SET   WHITE=%ESC%[1;37m
)
exit /b
::::::::::::::::::::::::::::::::
:BL.String.CreateDEL_ESC
::::::::::::::::::::::::::::::::
:: http://www.dostips.com/forum/viewtopic.php?t=1733
::
:: Creates two variables with one character DEL=Ascii-08 and ESC=Ascii-27
:: DEL and ESC can be used  with and without DelayedExpansion
setlocal
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  ENDLOCAL
  set "DEL=%%a"
  set "ESC=%%b"
  goto :EOF
)
::::::::::::::::::::::::::::::::
:supportsANSI
::::::::::::::::::::::::::::::::
:: returns ERRORLEVEL 0 - YES, 1 - NO
::
:: - Tests for ConEmu, ANSICON and Clink
:: - Returns 1 - NO support, when called via "CMD /D" (i.e. no autoruns / DLL injection)
::   on a system that would otherwise support ANSI.
if "%ConEmuANSI%" == "ON" exit /b 0
call :getPID PID
setlocal
for /f usebackq^ delims^=^"^ tokens^=^* %%a in (`tasklist /fi "PID eq %PID%" /m /fo CSV`) do set "MODULES=%%a"
set MODULES=%MODULES:"=%
set NON_ANSI_MODULES=%MODULES%
:: strip out ANSI dlls from module list:
:: ANSICON adds ANSI64.dll or ANSI32.dll
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ANSI=%"
:: ConEmu attaches ConEmuHk but ConEmu also sets ConEmuANSI Environment VAR
:: so we've already checked for that above and returned early.
@rem set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ConEmuHk=%"
:: Clink supports ANSI https://github.com/mridgers/clink/issues/54
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:clink_dll=%"
if "%MODULES%" == "%NON_ANSI_MODULES%" endlocal & exit /b 1
endlocal
exit /b 0
::::::::::::::::::::::::::::::::
:getPID  [RtnVar]
::::::::::::::::::::::::::::::::
:: REQUIREMENTS:
::
:: Determine the Process ID of the currently executing script,
:: but in a way that is multiple execution safe especially when the script can be executing multiple times
::   - at the exact same time in the same millisecond,
::   - by multiple users,
::   - in multiple window sessions (RDP),
::   - by privileged and non-privileged (e.g. Administrator) accounts,
::   - interactively or in the background.
::   - work when the cmd.exe window cannot appear
::     e.g. running from TaskScheduler as LOCAL SERVICE or using the "Run whether user is logged on or not" setting
::
:: https://social.msdn.microsoft.com/Forums/vstudio/en-US/270f0842-963d-4ed9-b27d-27957628004c/what-is-the-pid-of-the-current-cmdexe?forum=msbuild
::
:: http://serverfault.com/a/654029/306
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
  for /f "skip=1" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for %%B in (%%A) do set "PID=%%B"
  (call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b

Antwoord 11

Ik zal je eerst het antwoord geven waar je naar op zoek bent, voor degenen die niet veel uitleg willen lezen.

gebruik ANSI_escape_code.SGR_parameters

@echo off 
echo [38;2;255;255;0mHi[m [38;2;128;128;255mWorld[m 
pause > nul

👆 Vergeet niet ESC0x1B (Hex ), \033 (oktober), 27 (december)Virtuele sleutelcodes VK_ESCAPE

Ik raad u aan de bovenstaande inhoud te kopiëren (voor het geval u de ESC-sleutel mist) en deze vervolgens op de notepad++of andere IDE die je leuk vindt.

uitvoer zoals onderstaande afbeelding

voer hier de afbeeldingsbeschrijving in

Uitleg

volgens ANSI_escape_code.SGR_parametersdie je kent

. in

Nummer Naam Opmerking Voorbeeld
0 Reset of normaal Alle attributen uit ESC[0mof ESC[m
1 Boude of verhoogde intensiteit ESC[1m
3 Iktalic ESC[3m
4 Uonderstrepen ESC[4m
8 Verbergen of verbergen Niet breed ondersteund. ESC[8m
30–37 Voorgrondkleur instellen 30:zwart 31: rood, 32: groen, 33: geel, 34: blauw, 35: paars, 36: Aqua, 37: wit rood: ESC[31m
38 Stel voorgrondkleur Volgende argumenten zijn 5;n of 2;r;g;b rood: ESC[38m;2;255;0;0m
40–47 Achtergrondkleur instellen rood: ESC[41m
48 Stel achtergrondkleur Volgende argumenten zijn 5;n of 2;r;g;b rood: ESC[48m;2;255;0;0m

Other episodes