1

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)

Ben Jost
  • 309
  • 1
  • 3
  • 10
  • 4
    Possible Duplicate of: http://stackoverflow.com/questions/11657622/detect-or-intercept-moment-when-a-batch-is-closed-via-mouse-x-console-button – Leptonator Jan 13 '16 at 13:35
  • You would have to have another program that is monitoring that cmd.exe instance and have it do what you want it to do when you close the window. – Squashman Jan 13 '16 at 13:37
  • A sloppy possibility would be having a masin batch start your desired to watch batch with a `/wait` parameter. But then two windows would be opened.. – Bloodied Jan 13 '16 at 14:53

2 Answers2

2

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
Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

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.

HardCoded
  • 134
  • 2
  • 8