0

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();
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
lightning
  • 37
  • 4
  • You may want: [https://stackoverflow.com/questions/8713960/cmd-exe-k-switch](https://stackoverflow.com/questions/8713960/cmd-exe-k-switch) – drescherjm Mar 01 '22 at 16:22
  • No. I wanted to run the program via createprocess. – lightning Mar 01 '22 at 16:24
  • 1
    Yes but I think you need to execute `cmd /k init.bat` to run your batch file or use system() – drescherjm Mar 01 '22 at 16:25
  • Here is a duplicate: [https://stackoverflow.com/questions/25919451/use-createprocess-to-run-a-batch-file](https://stackoverflow.com/questions/25919451/use-createprocess-to-run-a-batch-file) – drescherjm Mar 01 '22 at 16:26
  • Also: [https://social.msdn.microsoft.com/Forums/en-US/259d3fe7-1f52-4068-bb12-32788104c798/createprocess-cannot-execute-batch-file?forum=vcgeneral](https://social.msdn.microsoft.com/Forums/en-US/259d3fe7-1f52-4068-bb12-32788104c798/createprocess-cannot-execute-batch-file?forum=vcgeneral) – drescherjm Mar 01 '22 at 16:28

1 Answers1

2

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.

Jens
  • 6,173
  • 2
  • 24
  • 43