Question

My question is how would I make a batch script instead of closing when the X in the top right is pressed to execute a file called exit.exe.

Was it helpful?

Solution 2

the [X] is "out of reach" for cmd. Only way, I can think of is: create another cmd to watch the presence of the current window:

@echo off
title WatchMe
more +7 %~f0 >t2.bat
start "watcher" t2.bat

exit /b

@echo off
:running
tasklist /v|find "WatchMe" >nul &&echo waiting || goto finished
timeout 1 >nul
goto running
:finished
echo "the process has finished

OTHER TIPS

There are a couple points in this question that are not clear enough:

  • If you want that when the rigth top X is pressed on the cmd.exe window it not close, but do a different thing instead, then there is no way to achieve such thing with any existent window, that is, with the windows of all existent applications.
  • If you want to differentiate if the window that execute your Batch file terminated normally or terminated because the user click on the right top X, then the way to achieve that is via a previous "starter" program that execute your Batch file and expects a certain value returned from it. If the returned value is not the expected one, then it is assumed that the window was cancelled via the right top X.

starter.bat:

@echo off

echo Start yourScript.bat:
start "" /W yourScript.bat
echo Value returned from the script: %errorlevel%
if %errorlevel% neq 12345 ECHO execute exit.exe

yourScript.bat:

@echo off

echo I am the script.bat
set /P var=input value:

rem Terminate normally:
exit 12345
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top