Is there a way to write Ctrl-C in a batch file?

Viewed 9802

Is there a way to use ctrl-c in a batch-file without the need for the user to input ctrl-c?


In batch files and command prompt, the input ctrl-c will break a command like a for loop or a batch job in general. I was messing around to see if the actual break command had any use (it really doesn't, even when command extensions are on it is useless) and I thought "is there a way to write ctrl-c in a batch file or on the command line?" The first thing that I tried was making a step for loop using for /l with an if statement in the do section saying if %a LEQ 9500 (^^C) as ^C is how it is shown when you inputctrl-c to break something. When I ran the full command (for /l %a in (10000, -1, 1) do (if %a LEQ 9500 (^^C))) it did the error '^C' is not recognized as an internal or external command, operable program or batch file. when %a got below 9500. I also tried this same thing in a batch file with %%a and it had the same error. I then tried using break as well with extensions on and off and still it didn't work.

What I want to learn

So overall I want to figure out the command-equivalent of ctrl-c and how to use it.

2 Answers

Check this thread

Here's the exit function by dbenham that uses -1073741510 as exit code to emulate ctrl-c in a .bat script:

:ExitBatch - Cleanly exit batch processing, regardless how many CALLs
if not exist "%temp%\ExitBatchYes.txt" call :buildYes
call :CtrlC <"%temp%\ExitBatchYes.txt" 1>nul 2>&1
:CtrlC
cmd /c exit -1073741510

:buildYes - Establish a Yes file for the language used by the OS
pushd "%temp%"
set "yes="
copy nul ExitBatchYes.txt >nul
for /f "delims=(/ tokens=2" %%Y in (
  '"copy /-y nul ExitBatchYes.txt <nul"'
) do if not defined yes set "yes=%%Y"
echo %yes%>ExitBatchYes.txt
popd
exit /b

Add this at the end of your script and you can just use call :ExitBatch

if you want to see the prompting message you call the :CtrlC function

The STATUS_CONTROL_C_EXIT method is language-dependent, that's why @dbenham included the

copy/-Y nul [ANY FILE THAT EXISTS]

which outputs

[Rubbish] (Yes/No/All)?

in this case, we obviously want Yes (or in whatever language the machine is running on), so delims=(/ is needed.


Here is a language-independent solution, like Ctrl-C, it terminates all batch processing immediately:

@echo off

FOR /L %%I in () do call:break 1000

NEVER REACHED

:break RETURN_EXIT_CODE
cmd /c exit %1
call:halt >nul 2>&1


:halt - Infinite Recursion
call:halt
Related