您的位置:首页 > 其它

【原创】关闭指定名字的进程,关闭指定id的进程, 取得指定进程的id

2012-10-16 21:30 405 查看
#include "stdafx.h"
#include <windows.h>
#include "tlhelp32.h"
#include <string>
#include <iostream>

using std::string;
using std::cout;
using std::endl;

// findprocessid
// find the process identifer with the specified process name
// proc_name [in] name of process
// return value : the identifer of process, if return value is 0, indicate that fail to get process identifer
DWORD FindProcessId(const char* proc_name_)
{
DWORD proc_id_ = 0;

PROCESSENTRY32 proc_entry_;
HANDLE handle_ = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(handle_ != INVALID_HANDLE_VALUE)
{
proc_entry_.dwSize = sizeof(proc_entry_);
if(Process32First(handle_, &proc_entry_))
{
do
{

if(stricmp(proc_entry_.szExeFile, proc_name_) == 0)
{
proc_id_ = proc_entry_.th32ProcessID;
break;
}
}while(Process32Next(handle_, &proc_entry_));
}
CloseHandle(handle_);
}
return proc_id_;
}

// TerminateProc
// Terminate a process that is specified by process identifer
// proc_id_ [in] indentifer of process
// return value : true -- successful, false -- fail
bool TerminateProc(DWORD proc_id_)
{
bool b_rtn = false;

HANDLE handle_ = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc_id_);
if(handle_ != INVALID_HANDLE_VALUE)
{
DWORD exit_code_;
GetExitCodeProcess(handle_, &exit_code_);
TerminateProcess(handle_, exit_code_);
WaitForSingleObject(handle_, INFINITE);
CloseHandle(handle_);
b_rtn = true;
}
return b_rtn;
}

// TerminateProcSZ
// Terminate a process that is specified by process window name
// win_name_ [in] name of process window
// return value : true -- successful, false -- fail
bool TerminateProcSZ(const char* win_name_)
{
bool b_rtn = false;

HWND h_wnd = FindWindow(NULL, win_name_);
if(!h_wnd)
{
return b_rtn;
}
::PostMessage(h_wnd, WM_CLOSE, 0,0);

DWORD proc_id_ = 0;
GetWindowThreadProcessId(h_wnd, &proc_id_);
HANDLE handle_ = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc_id_);
if(handle_ != INVALID_HANDLE_VALUE)
{
DWORD dw_wait = WaitForSingleObject(handle_, 2000);
if(dw_wait == WAIT_TIMEOUT)
{
DWORD exit_code_;
GetExitCodeProcess(handle_, &exit_code_);
TerminateProcess(handle_, exit_code_);
WaitForSingleObject(handle_, INFINITE);
}
CloseHandle(handle_);
b_rtn = true;
}
return b_rtn;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: