Detect or intercept moment when a batch is closed via mouse (X console button)

后端 未结 2 1231
栀梦
栀梦 2021-01-07 04:33

I need to run a batch \"Script A\" and this is only run either when the batch is closed programatically via the \"Do you want to exit [y / n] questions\" or when all the scr

相关标签:
2条回答
  • 2021-01-07 05:19

    The following simple scheme seems to work. The cleanup script calls the main script via the START command with the /WAIT option. This ensures control will return even if the child process is killed by closing the window.

    The parent cleanup script will normally prompt if you want to "Terminate batch job (Y/N)?" if the main script is killed by closing the window. I pipe N into the START command to automatically answer that prompt, should it arise. The outer block redirection of stderr to nul suppresses the ugly ^C (Control-C) that shows up when the main window is killed.

    The main batch file isn't STARTed directly, but instead is launched via the CMD /C command. This ensures control will return even if the main script is killed by pressing Control-C. This also eliminates the need to put an EXIT command in the main script (which might never be executed any way).

    cleanup.bat

    @echo off
    :: Launch the main program and don't continue until it completes (or is killed)
    2>nul (
      echo N|start /wait "" cmd /c main.bat
    )
    
    :: Cleanup up begins here
    echo Time to wrap it up!
    

    Here is a trivial main.bat to test the return functionality

    @echo off
    echo This is the main script.
    echo(
    echo    Press any key to close normally
    echo or Close this window via the console window X button
    echo or Press Ctrl-C to break out of this script abnormally
    pause >nul
    


    EDIT

    Of course there is nothing to prevent a user from closing the "cleanup.bat" window before the main script terminates, which puts you right back to square one :-(

    You can run a VBScript or Jscript via wscript without any visible window to close. The (VB/J)script can then launch the main.bat script and then launch a cleanup.bat script only when the main process finishes (or is killed). That would make it more difficult for an end user to interfere with the process of kicking off the cleanup script.

    master.vbs

    Set WshShell = CreateObject("WScript.Shell")
    WshShell.Run "D:\test\main.bat", 1, TRUE
    WshShell.Run "D:\test\cleanup.bat", 1, TRUE
    Set WshShell = Nothing
    

    But once you cross that threshould, why not do the entire project in (VB/J)script?

    0 讨论(0)
  • 2021-01-07 05:21

    A batch cannot tell when it gets closed from the red X. Therefore, any code handling the close from the X will have to come from somewhere else. One possibility would be to make another batch use TASKLIST to monitor when the first batch gets closed.

    0 讨论(0)
提交回复
热议问题