user2115945
user2115945

Reputation: 223

Windows C++ CMD window switching

Hello fellow programmers, I have a problem with some console applications in a C++ program, and my objective is as follows.

  1. Create first CMD window.
  2. Execute a command. (system("print some error text");)
  3. Create second CMD window.
  4. Change system(...) focus to second CMD window.
  5. Execute a command.
  6. Change system(...) focus to first CMD window.
  7. Execute a command.

The end goal of all this is to create a function that will be executed by a CMD application that will spawn another CMD window, execute a command on it, and then return focus to the original CMD window to continue executing other code. I do not need to keep track of the window, or be able to return to it. Just create new window, switch focus to it, execute a command, return focus to original window.


  1. The first CMD window is created when the application is started.
  2. Executing a command to this window with system(...); works fine.
  3. I create a second CMD window with

    HWND new_hWnd = NULL;
    ShellExecute(new_hWnd, "open", "cmd.exe", NULL, NULL, SW_SHOW);
    
  4. This is where I have problems, I have not been able to redirect system(...) to a different CMD window, and this is the part I need help with because if I can figure this out, then steps 5, 6 and 7 will be easy to complete.

I've tried researching this online and have come across some different examples using "pipes" but have not been able to recreate them, or understand them. Also, I noticed there is a

    GetConsoleWindow();

function that returns a handle to the current CMD window, which to me kinda signals that there should be a way to switch between CMD windows by using handles, but since I have not switched focus to the other CMD window I can not call that function to get it's handle.

So, how do I make system(...) target different CMD windows with handles? If that is not possible, how can I implement this "pipe" system.

If the solution is the latter, please try to be as detailed and simple as possible with it because every example of it I have found online is really large and hard to read/understand.

If there is no easy way to implement "pipes" then please post or point me to the best(something that will help me understand how pipes work) example you can find and I will keep working with it till I figure it out. Thank you in advance!

Upvotes: 0

Views: 452

Answers (1)

Ben
Ben

Reputation: 35613

You can create a new console for the new process by specifying the dwCreationFlags value CREATE_NEW_CONSOLE when calling CreateProcess.

See the documentation:

Upvotes: 1

Related Questions