References:
Find process ID by name and inject to it. Simple C++ example. C++ Get process handle by process name
The function is mainly for the auto-update service, executing subsequent functions after detecting that the program has exited.
When using the second reference, an error occurred. I found it was a stack overflow in the for loop, likely due to the field determination function, causing every program name to be judged correct. I recommend adopting the content from the first URL.
code:
#pragma once
#include <TlHelp32.h>
class CheckApplication
{
public:
CheckApplication();
private:
HANDLE getProcessHandle();
public:
int IsExit();
private:
const char* _Name = "Revit.exe";
};
#include "pch.h"
#include "CheckApplication.h"
CheckApplication::CheckApplication()
{
}
HANDLE CheckApplication::getProcessHandle()
{
BOOL hResult = NULL;
HANDLE hSnapShot = NULL;
PROCESSENTRY32 pe32 = { sizeof(pe32) };
DWORD pid = NULL;
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapShot)
return NULL;
hResult = Process32First(hSnapShot, &pe32);
while (hResult)
{
if (strcmp(pe32.szExeFile, _Name) == 0) {
pid = pe32.th32ProcessID;
break;
}
hResult = Process32Next(hSnapShot, &pe32);
}
//close handle
CloseHandle(hSnapShot);
HANDLE hHandle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
return hHandle;
}
int CheckApplication::IsExit()
{
HANDLE h = getProcessHandle();
if (h == NULL)
return -1;
//wait 10 seconds to close revit thread
DWORD dwRet = WaitForSingleObject(h,10000);
if (dwRet == WAIT_OBJECT_0)
return 1;
else
return 0;
}