【问题标题】:batch - simple one key stroke option批处理 - 简单的一键式选项
【发布时间】:2016-09-08 11:34:53
【问题描述】:

我想制作批处理文件,所以我可以静默安装应用程序

我想给执行批处理文件的用户一个选项 如果他们点击“空格键”,则安装继续,如果他们点击任何其他按键,则操作中止。

【问题讨论】:

  • @RC。暂停会根据按下的键返回不同的错误级别吗?
  • 我不知道,而且我没有 Windows 系统可供使用
  • 我很确定pause 根本不会修改ErrorLevel...
  • 这就是我问的原因。这无济于事,因为无法确定是否已按下空格键或其他键...

标签: batch-file choice


【解决方案1】:

这是一种使用 REPLACE 的稳健但不直观的方法。

@echo off
setlocal

echo Press [Space] to continue, any other key to abort...
set "space="
for /f "skip=1 delims=" %%A in ('replace.exe ? . /u /w') do if "%%A" equ " " set "space=1"
if defined space (
  echo CONTINUE
) else (
  echo ABORT
)

上面代码中的replace命令保证没有效果,但还是提示用户按键,按键以FOR /F可以捕获的方式回显到stdout。我第一次看到这种技术是在Password Input (new method)

使用 REPLACE 技术,我开发了一个例程,可以识别和存储从 0x00 到 0xFF 的所有单字节字符的按键:
Read key presses via REPLACE - New functions :getKey, :getAnyKey, :getMaskedInput

【讨论】:

    【解决方案2】:

    作为概念证明,这会读取任何击键(没有箭头或特殊键)并执行操作,如果它是 空格键

    @echo off
    
    SetLocal EnableDelayedExpansion
    
    set/a abort=1
    <NUL set/p="Hit space to continue, any oyher to abort "
    
    for /f "delims=" %%A in ('xcopy /w "%~f0" "%~f0" 2^>nul') do (if not defined key set "key=%%A") & set "key=!key:~-1!" & (if "!key!" equ " " set/a abort=0)
    
    if %abort% equ 1 (
      echo(&echo(&echo(* You have not pressed the spacebar key. Aborting... [your key: %key%]
    ) else (
      echo(&echo(&echo(* You have pressed the spacebar key. Have a nice day...
    )  
    EndLocal
    exit/B
    

    【讨论】:

      【解决方案3】:

      对于空格键的确定,它是相当沉重的,但你可以使用choice 让他们在单个按钮之间进行选择。

      像这样使用它:

      choice /c:AB /m "Abort ->A; Continue ->B"
      Goto:choice%errorlevel%
      :choice1
      REM Choice A
      :choice2
      REM Choice B
      

      该命令将内部变量errorlevel 设置为所选选项的编号。您可以在 /c 开关中设置不同的键,并使用 /m 设置消息。

      我不确定是否有空格键选项。 顺便说一句:其他键将被忽略。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-29
        • 1970-01-01
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 2017-08-03
        • 1970-01-01
        • 2019-01-26
        相关资源
        最近更新 更多