Execute batch code when user click on exit

2019-04-02 11:02发布

问题:

I am working on some code testing, and I stumbled on a problem I can't find or fix. My problem is:

If a user accidentally closes the cmd window, I'd like to execute a batch code before it actually closes. For example:

I run script A.bat . When a user wants to exit, I want it to delete my B.bat and then close the window.
This is how the code may look like:

@ECHO OFF
echo Welcome to A.bat
del B.bat (when user exits the window)

I couldn't find it on google and forums, so I thought maybe you guys could help me out. Thanks in advance, Niels

回答1:

This works for me:

@ECHO OFF
if "%1" equ "Restarted" goto %1
start "" /WAIT /B "%~F0" Restarted 
del B.bat
goto :EOF

:Restarted

echo Welcome to A.bat
echo/
echo Press any key to end this program and delete B.bat file
echo (or just close this window via exit button)
pause
exit

EDIT: Some explanations added

The start command restart the same Batch file in a new cmd.exe session; the /B switch open it in the same window and the /WAIT switch makes the original file to wait until the new one ends. The new Batch file must end with exit in order to kill the new cmd.exe session (because it was started with the /K switch). No matters if the new cmd.exe session ends normally because the exit command or because it was cancelled with the red X; in any case the control returns after the line that started it in the original execution.



回答2:

I've had to do something similar to what you're describing. I'm not sure whether this is the simplest or most efficient way to accomplish what you ask, but it does indeed work nevertheless.

@echo off
setlocal

:lockFile
rem // create lock file to inform forked helper thread when this thread completes
rem // credit to dbenham: http://stackoverflow.com/a/27756667/1683264
set "lockFile=%temp%\%~nx0_%time::=.%.lock"
9>&2 2>NUL (2>&9 8>"%lockFile%" call :main %*) || goto :lockFile
del "%lockFile%"
exit /b

:main
call :cleanup_watcher "B.bat"
rem // put your main script here
pause
goto :EOF

:cleanup_watcher <file> (<file> <file> etc.)
rem // Write external script to delete filename arguments
rem // (so if main script exits via ^C, temp files are still removed)
>"%temp%\tmp.bat" (
    echo @echo off
    echo setlocal
    echo :begin
    echo ping -n 1 -w 500 169.254.1.1 ^>NUL
    echo del /q "%temp%\%~nx0*.lock" ^>NUL 2^>NUL
    rem // If lockfile can't be deleted, the main script is still running.
    echo if exist "%temp%\%~nx0*.lock" goto :begin
    echo del /q "%temp%\tmp.bat" %* ^&^& exit
)

rem // fork cleanup watcher invisibly to catch ^C
>"%lockfile%.vbs" echo CreateObject("Wscript.Shell").Run "%temp%\tmp.bat", 0, False
wscript "%lockfile%.vbs"
del "%lockfile%.vbs"