1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 用到的头文件
#include "tlhelp32.h"

// szName获取窗口句柄
HANDLE CHungDlg::GetWindowHandle(const CString& szName)
{
return ::FindWindow(NULL, szName);
}
// 根据程序窗口句柄结束进程
BOOL CHungDlg::CloseApp(HANDLE handle)
{
DWORD nProcessID;
// 根据进程句柄获取进程ID
::GetWindowThreadProcessId((HWND)handle,&nProcessID);

return CloseApp(nProcessID);
}

// 根据进程ID结束进程
BOOL CHungDlg::CloseApp(DWORD ProcessId)
{
HANDLE hProcess = NULL;
hProcess = ::OpenProcess(PROCESS_TERMINATE,FALSE,ProcessId);
if (!::TerminateProcess(hProcess, 0))
{
DWORD derror = GetLastError();
return FALSE;
}
return TRUE;
}
// 根据进程名szName获取进程ID
BOOL CHungDlg::GetProcessID(const CString& szName, DWORD& ProcessID)
{
//获取进程快照
HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if (handle == INVALID_HANDLE_VALUE)
{
return FALSE;
}

PROCESSENTRY32 processList;
processList.dwSize=sizeof(PROCESSENTRY32);
BOOL bResult=Process32First(handle, &processList);
BOOL bReturn=FALSE;
while(bResult)
{
CString str=processList.szExeFile;
if(str==szName)
{
ProcessID = processList.th32ProcessID;
bReturn=TRUE;
break;
}
else
{
bResult=Process32Next(handle, &processList);
}
}
//清除掉handle对象
::CloseHandle(handle);
return bReturn;
}