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

前端 未结 6 1124
误落风尘
误落风尘 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:48

    GetConsoleTitle()

    I've seen code which performs

    if (!GetConsoleTitle(NULL, 0) && GetLastError() == ERROR_SUCCESS) {
        // Console
    } else {
        // GUI
    }
    

    BUT... I've found that AttachConsole() is more helpful

    In C++ (off the top of my head, and I'm no C++ programmer)

    if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
        // GUI
    } else {
        // Console, and you have a handle to the console that already exists.
    }
    

    Is more effective. Additionally, if you find yourself in a GUI environment and would like to stay there as long as you can, but later find something catastrophic has happened that could really use a dump to a console window (you can't be arsed writing an edit box window to lot it to or attach to the NT System log and throw up a MessageBox()) well then you can AllocConsole() later on in the process, when GUI methods have failed.

提交回复
热议问题