根据进程名判断进程是否运行

时间:2022-08-28 21:57:12

问题描述:

给定进程名,判断该进程是否正在运行。

参考代码:

#include <TlHelp32.h>

BOOL IsProcessRunning(LPCTSTR lpProcessName)
{
if (NULL == lpProcessName)
return FALSE;

HANDLE hProcess = NULL;
HANDLE hProcessSnap = NULL;
PROCESSENTRY32 Info = {0};
hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
Info.dwSize = sizeof(PROCESSENTRY32);
if(::Process32First(hProcessSnap,&Info))
{
do
{
CString ss = Info.szExeFile;

DWORD dwVersion = GetVersion();

DWORD dwHigh = dwVersion & 0x80000000;
DWORD dwLow = dwVersion & 0x000000FF;

if((dwHigh == 0x80000000) && (dwLow == 4))
{
int iFind ;
if (( (iFind = ss.Find(lpProcessName)) != -1 )&&( (iFind = ss.Find(lpProcessName)) > 0 ))
{
if ((iFind + _tcslen(lpProcessName) == ss.GetLength())&&(ss[iFind-1] == _T('\\')))
{
CloseHandle(hProcessSnap);
hProcessSnap = INVALID_HANDLE_VALUE;
return TRUE;
}
}
}
else
{
if(!ss.CompareNoCase(lpProcessName))
{
CloseHandle(hProcessSnap);
hProcessSnap = INVALID_HANDLE_VALUE;
return TRUE;
}
}
}while(::Process32Next(hProcessSnap,&Info));
}

if ( hProcessSnap != INVALID_HANDLE_VALUE )
{
::CloseHandle(hProcessSnap);
hProcessSnap = INVALID_HANDLE_VALUE;
}

return FALSE;
}

int _tmain(int argc, _TCHAR* argv[])
{
BOOL bRet = IsProcessRunning(L"kxescore.exe");
return 0;
}