ProcessManager.h 头文件:
#pragma once
class ProcessManager
{
public:
ProcessManager();
~ProcessManager();
public:
static unsigned int GetProcessID(wchar_t *cPorcessName);
static bool CloseProcess(unsigned int unProcessID);
};
ProcessManager.cpp 源文件:
#include"stdafx.h"
#include <Windows.h>
#include <Psapi.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <stdlib.h>
#include "ProcessManager.h"
#pragma comment(lib, "Psapi.lib")
ProcessManager::ProcessManager()
{
}
ProcessManager::~ProcessManager()
{
}
unsigned int ProcessManager::GetProcessID(wchar_t *cPorcessName)
{
HANDLE hProcess = NULL;
PROCESSENTRY32 prry;
prry.dwSize = sizeof(PROCESSENTRY32);
BOOL bRet;
wchar_t* pmbbuf = new wchar_t[260];
if (NULL == pmbbuf)
{
return 0;
}
hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
bRet = Process32First(hProcess, &prry);
while (bRet)
{
memset(pmbbuf, 0, 260);
swprintf_s(pmbbuf, 260, L"%s", prry.szExeFile);
if (0 == wcscmp(pmbbuf, cPorcessName))
{
//找到后返回进程ID
delete pmbbuf;
pmbbuf = NULL;
return prry.th32ProcessID;
}
else
{
//查找下一个进程
bRet = Process32Next(hProcess, &prry);
}
};
delete pmbbuf;
pmbbuf = NULL;
return 0;
}
bool ProcessManager::CloseProcess(unsigned int unProcessID)
{
HANDLE bExitCode = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE
| PROCESS_ALL_ACCESS, FALSE, unProcessID);
//WaitForSingleObject(bExitCode, INFINITE);
if (NULL != bExitCode)
{
BOOL bFlag = TerminateProcess(bExitCode, 0);
CloseHandle(bExitCode);
return true;
}
return false;
}
测试文件:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"ProcessManager.h"
#include<windows.h>
int main()
{
wchar_t* ProcessName = L"notepad.exe";
//ProcessNameToPid(ProcessName);
ProcessManager pro;
DWORD V = pro.GetProcessID(ProcessName);
pro.CloseProcess(V);
//GetProID(ProcessName);
return 0;
}