Hiding the DOS console on a console application on Windows

Eric Brunel eric.brunel at pragmadev.com
Mon Feb 4 14:17:16 EST 2002


Hi, and thanks for the answer,

> I'm sure you can build a straight windows gui app, and call AllocConsole()
> in the win32 API to pop up an associated console window if you want one.
> You don't have to build as a console app. Just do the AllocConsole() call
> when you want a console window.

We finally figured that out by ourselves, and did it. Unfornutaley, the 
AllocConsole functions does create a console window, and we still didn't 
want to see it.
We finally figured out a solution to make it disappear, and here it is, 
just for the record.
At first, the problem seemed simple: we only had to get the window handle 
of the console window, and pass it to ShowWindow as first argument with 
SW_HIDE as the second one. But we soon found out that there were no simple 
way to get the window handle for the console window...
So we finally used an o-so-dirty trick we found... in Micro$oft Visual C++ 
documentation! It is simply to change the title of the console window to a 
supposedly unique title via SetConsoleTitle, then get the handle of the 
window with that title via FindWindow...
Here is the actual C code we included in an external module:

// Don't make the console disappear if there was already one
if (AllocConsole())
        {
        // format a "unique" newWindowTitle
        wsprintf(newWindowTitle,"%d/%d",
                        GetTickCount(),
                        GetCurrentProcessId());
        // change current window title
        SetConsoleTitle(newWindowTitle);
        // ensure window title has been updated
        Sleep(40);
        // look for newWindowTitle
        hwndFound=FindWindow(NULL, newWindowTitle);
        // If found, hide it
        if ( hwndFound != NULL)
                ShowWindow( hwndFound, SW_HIDE);
        }

This is what I call an awful API! I'd never used such an ugly trick for 
years! ;-)
 - eric -



More information about the Python-list mailing list