简体   繁体   中英

How to Integrate Command prompt/Terminal in a Windows application?

Many programs like VS Code have a built-in terminal window that allows user to execute commands just as if they were working in command prompt or powershell. I'm working on adding similar functionality to my winforms application, and allow user to create multiple terminal windows.

I tried to do this by launching cmd.exe as a hidden process and redirecting stdin/stdout. But running into issues with synchronizing stdout & stderr output. There is no sure way of knowing where to insert stderr output in the stdout output and I often end up with out-of-place error messages - sometimes in-between stdout lines. If I use same handle for stderr/stdout, then output is synchronized correclty, however, I can't tell whether its error text so can't color code it.

Is my fundamental approach of running cmd.exe as a hidden process correct? If yes, then how do I merge output from stdout/stderr?

If I don't misunderstand, you may be able to do like below.

C++:

#include <windows.h>
#include <iostream>
void main()
{
    char cmd[] = "C:\\Windows\\System32\\cmd.exe";
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    CreateProcessA(cmd, NULL, NULL, NULL, FLASE, 0, NULL, NULL, &si, &pi);
    WaitForSingleObject(pi.hProcess, INFINITE);
}

with no dwCreationFlags flag, The child process cmd.exe and the parent process share the same console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM