0

Yes, I know you are probably going to complain saying it's a bad thing to do, but I want to do it anyway!

I am creating a batch program and at the end, I need it to hang and not accept user input. I know one method is just creating an infinite loop of:

    :pause
        pause > nul
        goto pause

but I don't think that's a great choice. Although I need it to hang, I need to to be able to be closed via the red 'X' close button at the top of the window.

Any ideas?

1 Answers1

1

This works for me. It redirects < NUL into self to prevent Ctrl+C from breaking, and uses start /b /wait to suppress the "Terminate batch job (Y/N)?" prompts.

@echo off
setlocal

>NUL (echo(%* | findstr "\<hang\>" && waitfor redX)

rem // *** PUT YOUR MAIN SCRIPT HERE ***
echo End of line.
rem // ******* END MAIN SCRIPT *********
call :hang
goto :EOF

:hang
start /b /wait "" "%~f0" hang ^<NUL

On the initial launch of the script, the echo(%* | findstr "\<hang\>" >NUL line looks for a script argument of "hang". If found, the script executes the waitfor command.

Normally, waitfor can be broken with Ctrl+C. But since the usual behavior of Ctrl+C is defeated by start /b and <NUL, the hanging effect is achieved unless a user does Ctrl+Break or sends the answering waitfor signal.

The red X still works, though.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • Great answer! That would be useful to others, but not me unfortunately. I have a big program and I'm testing for something, then, if it exists, hanging the cmd. –  May 14 '15 at 15:15
  • So why not `if problem exists ( call :hang )` then? – rojo May 14 '15 at 15:51