// cereatepross.cpp : 定義控制台應用程式的進入點。
//
#include "stdafx.h"
#include<iostream>
//#include<WinBase.h>
#include<Windows.h>
#include<TlHelp32.h>
#include<atlstr.h>
using namespace std;
BOOL FindAndKillProcessByName(LPCTSTR strProcessName);
int _tmain(int argc, _TCHAR* argv[])
{
FindAndKillProcessByName(L"cmd.exe");
return 0;
}
BOOL FindAndKillProcessByName(LPCTSTR strProcessName)
{
if(NULL == strProcessName)
{
return FALSE;
}
//為進程建立快照,在快照中包含系統中的所有進程
HANDLE handle32Snapshot =CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == handle32Snapshot)
{
return FALSE;
}
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof( PROCESSENTRY32 );
//Search for all the process and terminate it
//獲得第一個進程的控制代碼
if(Process32First(handle32Snapshot, &pEntry))
{
BOOL bFound = FALSE;
if (!_tcsicmp(pEntry.szExeFile, strProcessName))
{
bFound = TRUE;
}
while((!bFound)&&Process32Next(handle32Snapshot, &pEntry))
{
//比較
if (!_tcsicmp(pEntry.szExeFile, strProcessName))
{
bFound = TRUE;
}
}
if(bFound)
{
CloseHandle(handle32Snapshot);
//開啟一個已存在的進程對象,並返回進程的控制代碼
HANDLE handLe = OpenProcess(PROCESS_TERMINATE , FALSE, pEntry.th32ProcessID);
//結束指定進程和所有線程
BOOL bResult = TerminateProcess(handLe,0);
return bResult;
}
}
CloseHandle(handle32Snapshot);
return FALSE;
}