Can a Win32 console application detect if it has been run from the explorer or not?

前端 未结 6 1122
误落风尘
误落风尘 2020-12-13 12:49

I have to create a console application which needs certain parameters. If they are missing or wrong I print out an error message.

Now the problem: If someone starts

6条回答
  •  心在旅途
    2020-12-13 13:35

    EDIT: I've been using this .bat/.cmd wrapper successfully for a couple of years now:

    @ECHO OFF
    
    REM Determine if script was executed from an interactive shell
    (echo %CMDCMDLINE% | find /i "%~0" >NUL 2>&1) && (set IS_INTERACTIVE=false) || (set IS_INTERACTIVE=true)
    
    
    
    REM Wait for keystroke
    if "%IS_INTERACTIVE%" == "false" (
            echo.
            echo Hit any key to close.
            pause >NUL 2>&1
    )
    

    The advantage here is that this will work for all console applications, be it your own or someone else's (for which you might not have sources you could modify). The downside is, well, that you have a separate wrapper.


    My original answer back in 2014 was this:

    This works like a charm:

    @echo off
    for %%x in (%cmdcmdline%) do if /i "%%~x"=="/c" goto nonconsole
    
    :console
    
    goto exit
    
    :nonconsole
    
    pause
    
    :exit
    

    Copied from this thread. I also tried evaluating %cmdcmdline% myself, however there's an issue regarding quote characters ("), which prevents something like if "%cmdcmdline%" == "%ComSpec%" goto [target] from working.

提交回复
热议问题