Search code examples
c++winapicmdconsole-application

How can I create a whole new console window for a new cmd.exe process?


I'm in the process of creating a game engine inside a Windows 10 console. The goal now is to simulate frames. All is good with one exception - I need a way to display logs outside of the program before I get more into frame machine implementation. So I want to have a new process of a console in a new window just to do some logging in my debug compilations.

I've found the CreateProcess() function, however its documentation seems rather incomplete.

I filled the call as follows:

STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof si);
si.cb = sizeof si;
ZeroMemory(&pi, sizeof pi);

LPCWSTR appName { L"C:\\WINDOWS\\system32\\cmd.exe" };
//LPCWSTR appName { L"C:\\WINDOWS\\system32\\notepad.exe" };

CreateProcess (
    appName,        
    NULL,           
    NULL,           
    NULL,           
    FALSE,          
    0,              
    NULL,           
    NULL,           
    &si,            
    &pi         
)

I observed that the appName variable that points to Notepad creates a new window as expected, however when pointed to cmd it creates a process in the same console window.

How can I create a console process in a new window, from a console program?

I'm also open for other logger implementation ideas.


Solution

  • You can use the CREATE_NEW_CONSOLE or DETACHED_PROCESS flag in the dwCreationFlags parameter of CreateProcess(). See Process Creation Flags:

    Constant/value Description
    CREATE_NEW_CONSOLE 0x00000010 The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console. This flag cannot be used with DETACHED_PROCESS.
    DETACHED_PROCESS 0x00000008 For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console. This value cannot be used with CREATE_NEW_CONSOLE.

    But, why use a separate process for logging? Just have your main console process create a separate GUI window using CreateWindow/Ex(), and then it can display your log messages as needed, such as with a multi-line EDIT control, or a LISTVIEW control in report mode, etc. Then there will be no need to deal with inter-process communications, marshaling your log data across process boundaries.