Detect if bat file is running via double click or from cmd window

前端 未结 12 1697
醉话见心
醉话见心 2020-12-29 02:54

I have a bat file that does a bunch of things and closes the cmd window which is fine when user double clicks the bat file from explorer. But if I run the bat file from a al

12条回答
  •  不思量自难忘°
    2020-12-29 03:17

    A consolidated answer, derived from much of the information found on this page:

    :pauseIfDoubleClicked
    setlocal enabledelayedexpansion
    set testl=%cmdcmdline:"=%
    set testr=!testl:%~nx0=!
    if not "%testl%" == "%testr%" pause
    
    1. The variable "testl" gets the full line of the cmd processor call (as per mousio), stripping out all of the pesky double quotes.
    2. The variable "testr" takes "testl" and further strips outs the name of the current batch file name if present (which it will be if the batch file was invoked with a double-click).
    3. The if statement sees if "testl" and "testr" are different. If yes, batch was double-clicked, so pause; if no, batch was typed in on command line, go on.

    Naturally, if you want to do something else if you detect a double-click, you can change the pause.

    Thanks everyone.

提交回复
热议问题