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

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

    See http://support.microsoft.com/kb/99115, "INFO: Preventing the Console Window from Disappearing".

    The idea is to use GetConsoleScreenBufferInfo to determine that the cursor has not moved from the initial 0,0 position.

    Code sample from @tomlogic, based on the referenced Knowledge Base article:

    // call in main() before printing to stdout
    // returns TRUE if program is in its own console (cursor at 0,0) or
    // FALSE if it was launched from an existing console.
    // See http://support.microsoft.com/kb/99115
    #include 
    #include 
    int separate_console( void)
    {
        CONSOLE_SCREEN_BUFFER_INFO csbi;
    
        if (!GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE), &csbi))
        {
            printf( "GetConsoleScreenBufferInfo failed: %lu\n", GetLastError());
            return FALSE;
        }
    
        // if cursor position is (0,0) then we were launched in a separate console
        return ((!csbi.dwCursorPosition.X) && (!csbi.dwCursorPosition.Y));
    }
    

提交回复
热议问题