[SOLVED] Execute a bat file with parent process privilege in qt

Issue

I have a directory in the current working path of my executable which is called Store. In this directory, there is a bat file which is called init.bat. I have written the following code to run this file, but it seems CreateProcessW doesn’t run the bat file. How should I fix this code? I didn’t receive any error, the program just doesn’t work and my bat file doesn’t execute.

#include "mainwindow.h"

#include <QApplication>
#include <QSplashScreen>
#include <QMessageBox>
#include <QDir>

#include <windows.h>
#include <tchar.h>

#pragma comment(lib, "user32.lib")

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    bool status = FALSE;
    QSplashScreen *splash_loader = new QSplashScreen;
    splash_loader->setPixmap(QPixmap(":/new/prefix1/images/splash.png"));
    splash_loader->show();

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

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

    QString path = QDir::toNativeSeparators(qApp->applicationDirPath());
    path.append(L"\\Store\\init.bat");

    // Execute requirement batch file
    LPWSTR final_path = _wcsdup(path.toStdWString().c_str());

    status = CreateProcessW(NULL, final_path, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);

    if(status && WaitForSingleObject(pi.hProcess, INFINITE))
    {
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        splash_loader->close();
    }

    MainWindow w;
    w.show();
    return a.exec();
}

Solution

In Qt, you would use the QProcess-API (see QProcess::start()). Using CreateProcess is not the Qt way to do this.
In the linked documentation, you will find a hint on executing commands via cmd on Windows and hints for other OS.

Answered By – Jens

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *