The only way I can think of is to use a temporary file that holds the index of the clicked button.
Since this extends also the VBScript portion (due to the file creation code), I decided to place it in the batch script directly after the batch code. To identify it, every line is preceded with //
. (Regard that line continuation _
cannot be used there; environment variables like %TEMP%
cannot be used also.)
In the batch script portion, the VBScript lines are read by findstr /R "^//"
and a for /F
loop, all lines of the VBScript code are appended to each other, using separator :
. (Regard the limitation of command line length of about 8190 characters, which must not be exceeded by the entire VBScript.)
After having executed the mshta VBScript:Execute^("!SCRIPT!"^)
command line, the index of the clicked MsgBox
button is read from the temporary file (which is deleted immediately afterwards). Then the button name is displayed and the ErrorLevel
is set to the button index just for demonstration.
So here is the full code including some explanatory comments (save it with extension .bat
or cmd
):
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem /* Define constants here: */
set "BUTTON[1]=OK"
set "BUTTON[2]=Cancel"
set "BUTTON[3]=Abort"
set "BUTTON[4]=Retry"
set "BUTTON[5]=Ignore"
set "BUTTON[6]=Yes"
set "BUTTON[7]=No"
rem /* Read VBScript portion which is everything with leading `//`
rem (see the very bottom of this batch file): */
set "SCRIPT=" & set "SEP="
for /F "delims=" %%L in ('findstr /R "^//" "%~f0"') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*//=!"
set ^"LINE=!LINE:^"=""!^" & rem "
for /F delims^=^ eol^= %%S in ("!SCRIPT!!SEP!!LINE!") do (
endlocal
set "SCRIPT=%%S"
setlocal EnableDelayedExpansion
)
endlocal
set "SEP=: "
)
rem /* Execute VBScript here in the parent directory of this batch file;
rem this directory is going to contain a temporary text file then: */
setlocal EnableDelayedExpansion
cd /D "%~dp0"
mshta VBScript:Execute^("!SCRIPT!"^)
endlocal
rem /* Read the button index from the temporary text file and display: */
< "%~dp0msgbox_return_button.txt" set /P "INDEX="
del "%~dp0msgbox_return_button.txt"
call echo Button %%BUTTON[%INDEX%]%% ^(%INDEX%^) has been pressed.
rem /* Set `ErrorLevel` to the button index just as an example: */
cmd /C exit %INDEX%
endlocal
exit /B
/* VBScript */
//Set objFSO = CreateObject("Scripting.FileSystemObject")
//Set objTXT = objFSO.CreateTextFile(objFSO.BuildPath(objFSO.GetAbsolutePathName("."), "msgbox_return_button.txt"), True)
//objTXT.WriteLine(MsgBox("Please let me know:" & vbCrLf & "Is my answer helpful?", vbYesNo + vbQuestion, "StackOverflow"))
//objTXT.Close
//Close