1
votes

I want to open .exe file when qt application is started and terminate .exe when the qt application is closed.

QProcess *proc;

Calculator::Calculator(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Calculator)
{
    ui->setupUi(this);
    proc = new QProcess(this);
    QString fileName = "/ingredient";
    proc->start(fileName);
}

Calculator::~Calculator()
{
    delete ui;
    proc->waitForFinished();
    proc->terminate();
}

When I run Qt application, .exe is running. However, .exe is not terminated when I close the qt application, so what should i do?

2

2 Answers

1
votes

On windows you can use the windows API to kill the application. Remember, Qt will try to kill, but won't make sure to kill/end it. In the following code, change the with the name of your application and this will close it if you have enough privileges.

#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void YourClassName::killProcess()
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        if (_wcsicmp(pEntry.szExeFile, L"<AppName>.exe") == 0) // strcmp changed to _wcsicmp
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}
1
votes

Try proc->kill(); instead of proc->terminate();

According to the document, terminate() attempts to terminate the process, but may not exit the process.

It depends on how the .exe file handle the signal sent by terminate().

Besides, I think proc->waitForFinished(); is redundant in your code. It waits the process to finished, instead of telling the process to terminate.