Make batch file run in the background of the command prompt while continuing to use command prompt

batch filecommand linewindows

I am use a windows command prompt for hours a day at work, and I want to spice things up. I want my text color to change color every 1 second. I have a batch script that does this.

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%x in (%NUM%) do ( 
    for %%y in (%NUM%) do (
        color %%x%%y
        timeout 1 >nul
    )
)

It nicely changes the color of my foreground or background every second. However, I want to have this batch script run automatically whenever I open my command prompt shortcut. So in my Shortcut properties, I set the "Target" to this:

Shortcut Target:

C:\Windows\system32\cmd.exe /k auto-change-text-color.bat

This works as expected, but because the batch file is running, I cannot use the command prompt. And instead I just see the background color changing once in a while.

Is there any way to run this in the background and continue using the command prompt while the colors change?

If not, is there any other way to do what I want to do? Maybe with Java, perl, or something besides a batch file?

Thank you for your help.

Best Answer

It is a bit tricky, because you do not want the background color changing process to intercept any of your console input. You could add the /NOBREAK option to the TIMEOUT command, such that the script never reads stdin, except it still could process a <CTRL-Break> interupt, and ask if you want to terminate the script. The user could respond with Y and terminate the background process, but that could get confusing if the main process also has a running batch script. Which process gets the input?

You can redirect stdin to nul for the background process, but TIMEOUT fails if input is redirected.

I modified your auto-change-text-color.bat to use a PING delay instead of TIMEOUT, thus allowing stdin to be redirected to NUL. I also put one last COLOR command at the end to finish with a more readable color combination.

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%x in (%NUM%) do (
  for %%y in (%NUM%) do (
    color %%x%%y
    >nul ping localhost -n 2
  )
)
color 07

The following command is used to launch the script in the background with stdin redirected to nul:

start "" /b cmd /c "auto-change-text-color.bat <nul"

The only odd side effect is that the background process still can receive <CTRL-Break>, and it prints out the message Terminate batch job (Y/N)?, but immediately continues without waiting for input. So you can safely start a batch script in the main process, issue <CTRL-Break> and get two Terminate messages, and press Y or N knowing that only the batch script in your main process will respond (terminate or not).