简体   繁体   中英

Open Shell/CMD in C++

I would like to open a standard windows cmd using CreateProcessA(NULL, "cmd", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);

When executing the program, the console flashes briefly and then disappears How do I open the command line programmatically and leave it open for the user to enter arbitrary commands?

You need to use the /k option of cmd.exe , which keeps the console window open for user entry. The following snippet opens a new shell console and waits for the user to exit it using the exit command:

STARTUPINFOA si;   
ZeroMemory(&si,sizeof(STARTUPINFO));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
char cmd_exe[32767];
GetEnvironmentVariable("COMSPEC", cmd_exe, 32767);
if (CreateProcessA(cmd_exe, "/k", NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    DWORD dwExitCode = 0;
    GetExitCodeProcess(pi.hProcess, &dwExitCode);
    CloseHandle(pi.hProcess);
    std::cout << "cmd process exit code = " << dwExitCode << std::endl;
}
else
{
    DWORD dwErrorCode = GetLastError();
    std::cout << "cmd process not started, error = " << dwErrorCode << std::endl;
}

This is code that opens and waits for the process state to be changed:

if (CreateProcessA(NULL, "cmd.exe",
    NULL, NULL, TRUE, 0, NULL,
    NULL, &StartupInfo, &ProcessInfo))
{
    WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
}
else
{
    // Failed to launch ...
}

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