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

前端 未结 12 1657
醉话见心
醉话见心 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

    Less code, more robust:

    Build upon the other answers, I find the most robust approach to:

    1. Replace quotes with x to enable text comparison without breaking the IF statement.
    2. Recreate the expected cmdcmdline exactly (well, with '"' replaced by x).
    3. Test for case-insensitive equality.

    The result is:

    set "dclickcmdx=%systemroot%\system32\cmd.exe /c xx%~0x x"
    set "actualcmdx=%cmdcmdline:"=x%"
    
    set isdoubleclicked=0
    if /I "%dclickcmdx%" EQU "%actualcmdx%" (
        set isdoubleclicked=1
    )
    

    This adds more robustness against general cmd /c calls, since Explorer adds an awkward extra space before the last quote/x (in our favor). If cmdcmdline isn't found, it correctly renders isdoubleclicked=0.

提交回复
热议问题