NoFear

导航

查找目标程序并关闭【CSDN】

Posted on 2012-02-07 11:26  Fear_Hao  阅读(192)  评论(0编辑  收藏  举报
View Code
#include <stdio.h>
#include <string>
#include <Windows.h>
#include <Tlhelp32.h>


DWORD GetProcessVid(char* lpName)
{
HANDLE hProcessSnap = NULL;
BOOL bRet = FALSE;
PROCESSENTRY32 pe32 = {0};

if(!lpName)
{
return 0;
}

hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
return 0;

pe32.dwSize = sizeof(PROCESSENTRY32);

//是一个进程获取函数,当我们利用函数CreateToolhelp32Snapshot()获得当前运行进程的快照后,我们可以利用process32First函数来获得第一个进程的句柄
if (Process32First(hProcessSnap, &pe32))
{
do
{
//遍历比较进程名字是否相同
if(lstrcmp(CharUpper(pe32.szExeFile),CharUpper(lpName)) == 0)
{
CloseHandle (hProcessSnap);
return pe32.th32ProcessID;
}
}
while (Process32Next(hProcessSnap, &pe32));
bRet = 0;
}
else
bRet = 0;

CloseHandle (hProcessSnap);
return bRet;
}


int main()
{
char tmp[MAX_PATH];
memset(tmp,0,MAX_PATH);
//示范关闭notepad++.exe
lstrcpy(tmp,"notepad++.exe");

//查询进程号
DWORD pid = GetProcessVid(tmp);
if (pid != 0)
{
//打开一个已存在的进程对象,并返回进程的句柄
HANDLE hprocess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
if (hprocess != NULL)
{
TerminateProcess(hprocess,0);
CloseHandle(hprocess);
}
}
getchar();
return 0;

}