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

I am new to the Windows API and am programming in C ++. I would like to have a console to display information and receive keyboard commands through GetMessage. However, I cannot just create a console application, because if so, it is impossible to read keyboard messages sent to this console using GetMessage. Responding to keyboard input through GetMessage is a requirement for this project.

When I create a Win32 GUI application in Code :: Blocks 13.12 (using MinGW to compile) and call AllocConsoleat the beginning, I get error 5: "Access denied." If instead I use it first FreeConsole, FreeConsoleit will succeed without error; if I then use AllocConsole, a console window will appear. Description of MSDN FreeConsole:

Disconnects the calling process from its console.

This indicates that before the call to FreeConsole, the console already existed (although I could not see it and obviously did not create it). Is this an invisible console or does it always appear when starting the Code :: Blocks project? It makes no sense for me to use FreeConsole, and then AllocConsole? Is there a way to make the console already visible (if it is invisible) and is able to accept keyboard input through GetMessage?

Here is an example of 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;
}
+3
source share
1 answer

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

The explanation for your call AllocConsoleis that you are actually creating a console application . Despite what you use WinMain, mingw will still produce the default executable for the console subsystem. You can use a type tool dumpbinto check the PE header to confirm my conclusion.

-mwindows, , .

+1

All Articles