我是靠谱客的博主 奋斗草莓,最近开发中收集的这篇文章主要介绍[经验总结]Windows中关闭进程的C++实现,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

// [Added by thinkhy 09/12/20]
// Description: Kill process(es) by PID.
// Reference:   http://www.vckbase.com/document/viewdoc/?id=1882
// RETVALUE:    SUCCESS   TRUE
//              FAILED    FALSE
BOOL CProcessTool::KillProcess(DWORD dwPid)
{
         HANDLE hPrc;
 
         if( 0 == dwPid) return FALSE;
 
         hPrc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwPid);  // Opens handle to the process.
 
         if( !TerminateProcess(hPrc,0) ) // Terminates a process.
         {
                   CloseHandle( hPrc );
                   return FALSE;
         }
        else
            WaitForSingleObject(hPrc, DELAYTIME); // At most ,waite 2000  millisecond.
 
         CloseHandle(hPrc);
         return TRUE;
}
 
 
// [Added by thinkhy 09/12/20]
// Description: Kill process(es) by Name.
// Reference:   http://bbs.51testing.com/thread-65884-1-1.html
// RETVALUE:    SUCCESS   TRUE
//              FAILED    FALSE
BOOL CProcessTool::KillProcessByName(const TCHAR *lpszProcessName) {
    unsigned int   pid = -1;
    BOOL    retval = TRUE;
 
    if (lpszProcessName == NULL)
        return -1;
 
    DWORD dwRet = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS,0 );
    PROCESSENTRY32 processInfo;
    processInfo.dwSize = sizeof( PROCESSENTRY32 );
    int flag = Process32First( hSnapshot, &processInfo );
 
    // Find the process with name as same as lpszProcessName
    while (flag != 0)
    {
        if (_tcscmp(processInfo.szExeFile, lpszProcessName) == 0) {
              // Terminate the process.
              pid = processInfo.th32ProcessID;
              HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
 
              if (TerminateProcess(hProcess, 0) != TRUE) { // Failed to terminate it.
                  retval = FALSE;
                  break;
              }
        }
 
        flag = Process32Next(hSnapshot, &processInfo); 
    } // while (flag != 0)
 
    CloseHandle(hSnapshot);
 
    if (pid == -1)
        return FALSE;
 
    return retval;
}

最后

以上就是奋斗草莓为你收集整理的[经验总结]Windows中关闭进程的C++实现的全部内容,希望文章能够帮你解决[经验总结]Windows中关闭进程的C++实现所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部