Thursday, November 6, 2025

Randomly Set CMD Window Background Color

Before setting the console background color randomly, do the following to see the concepts behind this. 
Open CMD window and Run the following command: 

>COLOR 2E

It will set windows background color Green and foreground Light Yellow.

>COLOR/?

It will show you the helpful information about COLOR command. This command sets the default console foreground and background colors. 

COLOR [attr]    

The attr specifies color attribute of console output. Color attributes are specified by TWO hex digits - the first corresponds to the background; the second the foreground. Each digit can be any of the following values:

Color Code

0 = Black

  8 = Gray

1 = Blue

9 = Light Blue

2 = Green

  A = Light Green

3 = Aqua

B = Light Aqua

4 = Red

C = Light Red

5 = Purple

 D = Light Purple

6 = Yellow

 E = Light Yellow

Example: COLOR 2E will set background Green and foreground Light Yellow.

Note: You can use A, B, C, D and E hex digit in upper or lowercase.

If no argument is given, this command restores the color to what it was when CMD.EXE started.  This value either comes from the current console window, the /T command line switch or from the DefaultColor registry value. 

The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR command with a foreground and background color that are the same.  Example: "COLOR fc" produces light red on bright white

Example
We can use the built-in %RANDOM% environment variable and the modulo operator (%%) to generate random numbers between 0 and 9 and then colorize the windows randomly. The following script randomly colorize background color while foreground color is light yellow color(E)

@echo off
REM Generate a random number between 0 and 9
set /a RANDOM_DIGIT=%RANDOM% %% 10

echo The random number (0-9) is: %RANDOM_DIGIT%
COLOR %RANDOM_DIGIT%E

pause

No comments:

Post a Comment

Hot Topics