Reputation: 329
I want to create a batch file, that detects when the CMD window gets closed and does directly after an action.
If for example the the textfile text.txt is opened, and after i launch the batch file called prog.bat with this code inside:
@echo off
echo Hello
pause
How can i tell the batch that if the CMD window which is currently opend, should taskill text.txt file when somebody closes the CMD window?(by closing with ending process or hitting the X on the top)
Upvotes: 1
Views: 2944
Reputation: 67296
This is the accepted answer at this question:
@echo off
if "%1" equ "Restarted" goto %1
start "" /WAIT /B "%~F0" Restarted
echo Execute here anything you want when the Batch file is closed...
goto :EOF
:Restarted
echo Hello
pause
exit
Upvotes: 2
Reputation: 134
Im not one of the best but you could do this.
You need to create 3 files.
Start.bat
@echo off
TITLE Start.bat
REM :: THIS FILE OPEN'S THE CHECK WINDOW BATCH ::
start Init2.bat
ping localhost -n 1 >nul
REM :: IF I WOULDN'T HAVE THE "PING" THE CHECK WINDOW BATCH WOULD BE ON TOP ::
start Init1.bat
Init1.bat
@echo off
REM :: YOU CAN WRITE WHAT YOU WANT HERE ::
REM :: YOUST REMEMBER TO CHANGE "Init2.bat" WHEN YOU CHANGE THE TITLE ::
TITLE Init1.bat
echo.HELLO
pause>nul
Init2.bat
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
TITLE Init2.bat
:Start
REM :: GET PID ::
set "PID="
for /F "skip=3 delims=" %%A in ('TASKLIST /FI "WINDOWTITLE eq Init1.bat"') do (
set "A=%%A"
set "A=!A:~26,8!"
set "A=!A: =!"
set "PID=!A!"
set "A="
echo.!PID!
goto Test
)
REM :: IF NO WINDOWS NAMED "Init1.bat" exit ::
if not defined "PID" (
echo.No Window!
goto Exit
)
:Test
set "true=0"
for /F "skip=3 delims=" %%A in ('TASKLIST /FI "PID eq !PID!"') do (
set "true=1"
)
REM :: IF WINDOW CLOSED ::
if "!true!" EQU "0" (
echo.No Window!
goto Exit
)
goto Test
:Exit
REM :: HERE ARE YOU WRITING THE CLOSING FILE ::
ren testtxt.txt prog.bat
echo.@echo off > prog.bat
echo.echo hello >> prog.bat
echo.pause >> prog.bat
exit
Hope this help.
This is not a wiki answer, but i hope you find it helpful.
The only thing is that you have a window behind the first, but it works.
Upvotes: 0