一个批处理文件中的 2 个选择命令混淆了

一个批处理文件中的 2 个选择命令混淆了

例子:

@echo off
goto menu1

:menu1
cls
echo Menu 1
echo.
echo Press "1" to start control panel
echo.
echo Press "2" to go to second menu
echo.
choice /c 12
if errorlevel ==2 goto menu2
if errorlevel ==1 goto control panel


:menu2
cls
echo Menu 2
echo.
echo Press "1" start msconfig
echo.
echo Press "2" to go to first menu
echo.
choice /c 12
if errorlevel ==2 goto menu1
if errorlevel ==1 goto msconfig


:control panel
cls
start control
goto menu1


:msconfig
cls
start msconfig
goto menu1

所以如果我在菜单1然后我按 2,它会转到菜单2

如果我在菜单2然后我按 2,它会转到菜单1

但如果我在菜单2我按 1 打开 msconfig,但它打开的是控制面板菜单1尽管菜单2还开着呢,这是为什么呢?

答案1

为此,您可以(应该)使用 if 命令而不是错误级别。您还需要获取用户对变量的输入,例如 set /p examplemenu1= Enter your choice^> 这会将用户选择的内容插入到 examplemenu1,然后使用 if 命令。

我将向您展示一种编写菜单的更好方法,并解决您的问题。在此菜单中,如果有人不输入任何内容,则不会发生任何事情。

@echo off
:start
:menu1
cls
echo.
echo.
echo Enter 1 and Press Enter to open control panel
echo.
echo Enter 2 and Press Enter to go menu 2
echo.
set /p menu1= Enter your choice then Press Enter^>
if "%menu1%" EQU "1" goto :open-control
if "%menu1%" EQU "2" goto :menu2
goto :menu1

:menu2
Cls
REM I will do the basics
echo Menu 2
echo Type 1 to open msconfig
echo.
echo Type 2 to go back to menu 1
echo.
set /p menu2= Enter your choice and press enter^>
if "%menu2%" EQU "1" goto :open-msconfig
if "%menu2%" EQU "2" goto :menu1
goto :menu2

:open-control
cls
start control
REM People will ping a invalid host to wait
REM But they don't know that you can just use localhost
ping localhost -n 3 >nul
goto :start

:open-msconfig
Cls
start msconfig
ping localhost -n 3 >nul
goto :start

测试一下,如果有用的话就回复。

相关内容