DarkSidds
DarkSidds

Reputation: 193

QProcess with 'cmd' command does not result in command-line window

I am porting code from MinGW to MSVC2013/MSVC2015 and found a problem.

QProcess process;
QString program = "cmd.exe";
QStringList arguments = QStringList() << "/K" << "python.exe";
process.startDetached(program, arguments);

When I use MinGW, this code results in command-line window. But when I use MSVC2013 or MSVC2015, the same code results in cmd-process running in background without any windows. Are there any ways to make command-line window appear?

Upvotes: 2

Views: 2706

Answers (2)

Jason C
Jason C

Reputation: 40406

You don't need to use QProcess for this. It's much simpler to just use std::system:

#include <cstdlib>

// then when you want to open a 
// detached command prompt:
std::system("cmd");

You can also do things like:

std::system("cd some/path && cmd");

It's standard C++ (from C) so std::system(...) itself will work on any platform, only thing you need to set per platform is the shell command.

Upvotes: 0

DarkSidds
DarkSidds

Reputation: 193

The problem was connected with msvc2015, not with Qt5.8.0. There is the way to escape it. The idea is to use CREATE_NEW_CONSOLE flag.

#include <QProcess>
#include <QString>
#include <QStringList>
#include "Windows.h"

class QDetachableProcess 
        : public QProcess {
public:
    QDetachableProcess(QObject *parent = 0) 
        : QProcess(parent) {
    }
    void detach() {
       waitForStarted();
       setProcessState(QProcess::NotRunning);
    }
};

int main(int argc, char *argv[]) {
    QDetachableProcess process;
    QString program = "cmd.exe";
    QStringList arguments = QStringList() << "/K" << "python.exe";
    process.setCreateProcessArgumentsModifier(
                [](QProcess::CreateProcessArguments *args) {
        args->flags |= CREATE_NEW_CONSOLE;
        args->startupInfo->dwFlags &=~ STARTF_USESTDHANDLES;
    });
    process.start(program, arguments);
    process.detach();
    return 0;
}

Upvotes: 4

Related Questions