[C++]如何取得某個執行檔是否正在執行
發表於 : 2008年 11月 27日, 16:40
使用 tlhelp32 中的 CreateToolhelp32Snapshot 配合 Process32First, Process32Next 即可順利取出所有正在執行的執行檔名.
以下為檢查某一執行檔是否正在執行的範例, 傳回 true 則表示正在執行, false 則反之!
為了能在 win95/98/me 中可以順利使用, 修改了一下比對的方式, 在 win95/98/me 中, 列舉出來的 pe32.szExeFile 為含路徑的全名, 而在 win xp/2000 中則僅有檔名, 所以會有不同, 請參考!
以下為檢查某一執行檔是否正在執行的範例, 傳回 true 則表示正在執行, false 則反之!
代碼: 選擇全部
#include <tlhelp32.h>
..
BOOL ProcessExists(char *szExename)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
BOOL ret;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_value )
{
return( FALSE );
}
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap );
return( FALSE );
}
ret = false;
do
{
if(0 == stricmp(szExename, pe32.szExeFile))
{
ret = true;
break;
}
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( ret );
}
為了能在 win95/98/me 中可以順利使用, 修改了一下比對的方式, 在 win95/98/me 中, 列舉出來的 pe32.szExeFile 為含路徑的全名, 而在 win xp/2000 中則僅有檔名, 所以會有不同, 請參考!
代碼: 選擇全部
BOOL ProcessExists(char *szExename)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
BOOL ret;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_value )
{
return( FALSE );
}
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap );
return( FALSE );
}
ret = false;
int ilen = strlen(szExename);
do
{
// since pe32.szExeFile is MAX_PATH bytes, we can
// adjust the compare string starting position to use under
// win95/98/me (because the pe32.szExeFile is full name not
// only filename under win95/98/me)
int ipos = strlen(pe32.szExeFile)-ilen;
if(0 == stricmp(szExename, pe32.szExeFile + ipos))
{
ret = true;
break;
}
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( ret );
}