#include <QCoreApplication>
#include <QObject>
#include <QTimer>
#include <QString>
#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
QString fullname;
void check_and_restart(){
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE snap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if (snap == INVALID_HANDLE_VALUE){
std::cout << "CreateToolhelp32Snapshot failed." << std::endl;
return;
}
BOOL more = ::Process32First(snap,&pe32);
bool exists = false;
QString name = fullname.mid(fullname.lastIndexOf('\\'));
while (more){
if (name.compare(QString::fromWCharArray(pe32.szExeFile)) == 0){
exists = true;
HWND hwnd = ::FindWindow(NULL, name.toStdWString().c_str());
if (hwnd != NULL){
HINSTANCE hdll = ::LoadLibrary(L"user32.dll");
if (NULL != hdll){
typedef BOOL(WINAPI *PROCISHUNGAPPWINDOW)(HWND);
PROCISHUNGAPPWINDOW IsHungAppWindow = (PROCISHUNGAPPWINDOW)GetProcAddress(hdll, "IsHungAppWindow");
if (IsHungAppWindow(hwnd)){
//kill and restart
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS,TRUE,pe32.th32ProcessID);
TerminateProcess(proc,0);
::CloseHandle(proc);
goto restart;
}
}
}
::CloseHandle(snap);
return;
}
more = ::Process32Next(snap,&pe32);
}
::CloseHandle(snap);
//restart
if (!exists){
goto restart;
}
restart:
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = TRUE;
if (CreateProcess(fullname.toStdWString().c_str(),NULL,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)){
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
}
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
if (argc < 2){
std::cout << "wrong arguments." << std::endl;
}
fullname = QString(argv[1]);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, check_and_restart);
timer.start(1000);
return a.exec();
}