#include <Tlhelp32.h>
#include <stdio.h>
void KillProcess(LPTSTR sProcessName)
{
char cTemp[256];
//判该程序是否运行
HANDLE hProcessSnap = NULL;
PROCESSENTRY32 pe32={0};
PROCESS_INFORMATION ProcessInfo;
STARTUPINFO StartupInfo = {0};
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == (HANDLE)-1)
return;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hProcessSnap, &pe32))
{
do
{
if (strcmp(pe32.szExeFile,sProcessName) == 0)
{
StartupInfo.cb = sizeof(STARTUPINFO);
StartupInfo.wShowWindow = SW_HIDE;
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
sprintf(cTemp,"ntsd -c q -p %d", pe32.th32ProcessID);
CreateProcess(NULL,cTemp,NULL,NULL,FALSE,0,NULL,NULL,&StartupInfo,&ProcessInfo);
CloseHandle(hProcessSnap);
return;
}
}while (Process32Next(hProcessSnap, &pe32));
}
CloseHandle(hProcessSnap);
}
假设已知应用程序全路径名称:
LPTSTR lpszProcName = "E://项目文档与程序//BeatTest//BeatTest.exe";
那么如下调用即可杀死已有进程。
LPTSTR lpExeName = strrchr(lpszProcName, '//');
KillProcess(lpExeName + 1);