Here is one possible solution:
@echo off
title Firefox Watcher
setlocal EnableExtensions DisableDelayedExpansion
set "MusicPlay="
:Loop
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq Firefox.exe" /NH 2>nul | %SystemRoot%\System32\find.exe /I "firefox.exe" || goto NoFirefox
if defined MusicPlay goto WaitTime
start "" "%ProgramFiles%\KMPlayer 64X\KMPlayer64.exe" "%UserProfile%\Desktop\Apple.mp3"
if not errorlevel 1 set "MusicPlay=1"
goto WaitTime
:NoFirefox
if not defined MusicPlay goto WaitTime
%SystemRoot%\System32\taskill.exe /IM KMPlayer64.exe >nul 2>nul
set "MusicPlay="
:WaitTime
cls
%SystemRoot%\System32\choice.exe /C NY /N /T 5 /D N /M "Stop watching Firefox [N/y]?"
if not errorlevel 2 goto Loop
if defined MusicPlay %SystemRoot%\System32\taskill.exe /IM KMPlayer64.exe >nul 2>nul
endlocal
There could used for the command block below label WaitTime
also just:
%SystemRoot%\System32\timeout.exe /T 5 /NOBREAK >nul
goto Loop
That results in a timeout of five seconds without a user prompt to stop watching Firefox with waiting only up to five seconds for the user input before running the check on running Firefox once again.
A wait time with CHOICE or TIMEOUT (or PING) is necessary to pause batch script execution for some time like five seconds as otherwise the Windows command processor cmd.exe
would execute the commands in the batch file again and again as fast as possible which means cmd
would use one core of the CPU at 100% and would make really lots of file system accesses because of starting the executable TASKLIST again and again without any longer pause between the executions. That would not be good for the entire computer performance on which the music player runs and Firefox wants also CPU performance and access to the file system.
It would be better to replace the shortcut to start Firefox by a shortcut which starts cmd.exe
with the command line to start the music player as separate process, run Firefox and wait for its self-termination and then terminate the music player. That would be more efficient.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
cls /?
choice /?
echo /?
endlocal /?
find /?
goto /?
if /?
set /?
setlocal /?
start /?
taskkill /?
tasklist /?
timeout /?
title /?
See also: