C++ 检测程序是否在运行

参考材料:

Find process ID by name and inject to it. Simple C++ example.
C++通过进程名获取进程句柄

函数原因主要是为了服务自动更新的函数,在检测到程序退出后执行后续函数。

使用第二个引用的时候报错,发现是for循环堆栈溢出,应该是字段判定函数的问题,导致每个程序的名称都判定正确,建议采取第一个网址中的内容。

code:

#pragma once
#include 
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;
}


你可能感兴趣的:(C++,Revit二次开发,c++,开发语言)