批处理文件在关闭后执行操作

时间:2016-01-13 13:29:05

标签: windows batch-file cmd

我想创建一个批处理文件,该文件检测CMD窗口何时关闭并在操作后直接执行。

例如,如果打开文本文件text.txt,并且在我启动名为prog.bat的批处理文件后,其中包含以下代码:

@echo off

echo Hello

pause

如何告诉批处理当前正在打开的CMD窗口,当有人关闭CMD窗口时,应该是taskill text.txt文件吗?(通过关闭结束进程或点击顶部的X)

2 个答案:

答案 0 :(得分:1)

这是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

答案 1 :(得分:0)

我不是最好的,但你可以做到这一点。

您需要创建3个文件。

的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

希望得到这个帮助。

这不是维基的答案,但我希望你觉得它有用。

唯一的问题是你在第一个窗口后面有一个窗口,但是它有效。