In my case , i am running a batch file called file.bat

when my users close it using top right corner [X] close button, i like it need to run some programs before closing..

For example, i want my program to hide itself before closing , by running few command lines when user close the batch running cmd. (using [X] close button)

ren file.bat file.bak
attrib +s +h file.bak

i want to run this two command lines at the end of the program before users close it using top right close button [X] . So pls help me guys. i have no idea how to do that. So much of thanks in advance. Pls help..

  • Nope. Not how it works. Well, it could with a custom program which violates the typical standard, but unlikely for a batch file. The standard is: that X button closes things. What you might want to do is have file.bat quickly start a background program, which then runs file2.bat which does what you want. And if file2.bat is closed, the background program will then perform whatever clean-up measures you want. I'm not sure if this is worth the effort, but should work. I've found "ren" can be fragile: what if file.bak exists? Then ren file.bat fails. Just copy file.bak file.bat when needed. – TOOGAM Aug 15 '17 at 6:46
  • 1

So what you have to do is create a wrapper batch script which we will run invisibly using VBScript. That batch file will open another command window for the main batch script you wish to run, and when that script is ended by any means it will carry our the remaining commands within the script

'Run Batch Invisible
CreateObject("Wscript.Shell").Run chr(34) & "C:\Path\Script Files\Wrapper.cmd" & Chr(34), 0, False

Then we have wrapper.cmd:

REM Script: Wrapper.cmd
REM This script will Open another window, which, when closed will run a couple of commands.
SET "_BatchPath=C:\Path\Script Files"
SET "_BatchName=Your_Existing_Batch"
CALL START /WAIT "%_Batch%\%_BatchName%.bat"
MOVE /Y "%_Batch%\%_BatchName%.bat" "%_Batch%\%_BatchName%.bak"
Attrib +s +h "%_Batch%\%_BatchName%.bak"

This example is using the example commands you put forth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.