1 #include "stdafx.h"
2 #include <windows.h>
3 #include "tlhelp32.h"
4 #include <string>
5 #include <iostream>
6
7 using std::string;
8 using std::cout;
9 using std::endl;
10
11 // findprocessid
12 // find the process identifer with the specified process name
13 // proc_name [in] name of process
14 // return value : the identifer of process, if return value is 0, indicate that fail to get process identifer
15 DWORD FindProcessId(const char* proc_name_)
16 {
17 DWORD proc_id_ = 0;
18
19 PROCESSENTRY32 proc_entry_;
20 HANDLE handle_ = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
21 if(handle_ != INVALID_HANDLE_VALUE)
22 {
23 proc_entry_.dwSize = sizeof(proc_entry_);
24 if(Process32First(handle_, &proc_entry_))
25 {
26 do
27 {
28
29 if(stricmp(proc_entry_.szExeFile, proc_name_) == 0)
30 {
31 proc_id_ = proc_entry_.th32ProcessID;
32 break;
33 }
34 }while(Process32Next(handle_, &proc_entry_));
35 }
36 CloseHandle(handle_);
37 }
38 return proc_id_;
39 }
40
41 // TerminateProc
42 // Terminate a process that is specified by process identifer
43 // proc_id_ [in] indentifer of process
44 // return value : true -- successful, false -- fail
45 bool TerminateProc(DWORD proc_id_)
46 {
47 bool b_rtn = false;
48
49 HANDLE handle_ = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc_id_);
50 if(handle_ != INVALID_HANDLE_VALUE)
51 {
52 DWORD exit_code_;
53 GetExitCodeProcess(handle_, &exit_code_);
54 TerminateProcess(handle_, exit_code_);
55 WaitForSingleObject(handle_, INFINITE);
56 CloseHandle(handle_);
57 b_rtn = true;
58 }
59 return b_rtn;
60 }
61
62 // TerminateProcSZ
63 // Terminate a process that is specified by process window name
64 // win_name_ [in] name of process window
65 // return value : true -- successful, false -- fail
66 bool TerminateProcSZ(const char* win_name_)
67 {
68 bool b_rtn = false;
69
70 HWND h_wnd = FindWindow(NULL, win_name_);
71 if(!h_wnd)
72 {
73 return b_rtn;
74 }
75 ::PostMessage(h_wnd, WM_CLOSE, 0,0);
76
77 DWORD proc_id_ = 0;
78 GetWindowThreadProcessId(h_wnd, &proc_id_);
79 HANDLE handle_ = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc_id_);
80 if(handle_ != INVALID_HANDLE_VALUE)
81 {
82 DWORD dw_wait = WaitForSingleObject(handle_, 2000);
83 if(dw_wait == WAIT_TIMEOUT)
84 {
85 DWORD exit_code_;
86 GetExitCodeProcess(handle_, &exit_code_);
87 TerminateProcess(handle_, exit_code_);
88 WaitForSingleObject(handle_, INFINITE);
89 }
90 CloseHandle(handle_);
91 b_rtn = true;
92 }
93 return b_rtn;
94 }