您的位置:首页 > 编程语言 > C语言/C++

[经验总结]Windows中关闭进程的C++实现

2009-12-20 21:56 295 查看
// [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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息