Cerran
Cerran

Reputation: 2267

Can I use the default console in a Win32 GUI application, or should I create a new one?

I'm new to the Windows API and am programming in C++. I would like to have a console to output information to and receive keyboard commands via GetMessage. However, I can't just create a console application because if I do, it's impossible to read keyboard messages sent to that console with GetMessage. Reacting to keyboard input via GetMessage is a requirement for this project.

When I create Win32 GUI application in Code::Blocks 13.12 (using MinGW to compile) and call AllocConsole at the beginning, I get error 5: "Access is denied". If I instead first use FreeConsole, FreeConsole succeeds without error; if I then use AllocConsole, a console window appears. The MSDN description of FreeConsole is:

Detaches the calling process from its console.

This indicates that before I call FreeConsole, a console already existed (even though I couldn't see it and didn't explicitly create it). Is it an invisible console, or is it the one that always appears when running a Code::Blocks project? Is it pointless for me to use FreeConsole and then AllocConsole? Is there instead a way to make the console that already exists visible (if it's invisible) and able to receive keyboard input via GetMessage?

Here's an example of the stripped-down code that exhibits this behavior:

#include <windows.h>

DWORD dw = 0;

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nCmdShow)
{
    if (FreeConsole() == 0) {
        dw = GetLastError();
        return dw;
    }

    if (AllocConsole() == 0) {
        dw = GetLastError();
        return dw;
    }
    return 1;
}

Upvotes: 3

Views: 1115

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

When I create Win32 GUI application in Code::Blocks (using MinGW to compile) and call AllocConsole at the beginning, I get error 5: Access is denied.

The explanation for your call to AllocConsole failing is that you are actually building a console application. Even though you use WinMain, mingw will still produce, by default, an executable that targets the console subsystem. You can use a tool like dumpbin to inspect the PE header to confirm my conclusion.

Compile with -mwindows to make sure that the executable targets the GUI subsystem.

Upvotes: 1

Related Questions