[C++]如何取得某個執行檔是否正在執行

有關於C/C++的語法, 程式等
回覆文章
頭像
tim
文章: 1379
註冊時間: 2008年 11月 26日, 00:49

[C++]如何取得某個執行檔是否正在執行

文章 tim »

使用 tlhelp32 中的 CreateToolhelp32Snapshot 配合 Process32First, Process32Next 即可順利取出所有正在執行的執行檔名.

以下為檢查某一執行檔是否正在執行的範例, 傳回 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 ); 
    } 
多多留言, 整理文章, 把經驗累積下來.....
回覆文章