windows C++根据进程名杀死进程

#include <afxwin.h>
#include <tlhelp32.h>

HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32* processInfo = new PROCESSENTRY32;
processInfo->dwSize = sizeof(PROCESSENTRY32);
unsigned int index = 0, ID = 0;
while (Process32Next(hSnapShot, processInfo) != FALSE)
{
	index++;
	//WideCharToMultiByte需项目为unicode编码(宽字符wchar),
	//若为多字节编码(ASCII、GB2312、GBK等char),需将processInfo->szExeFile改为wexefile 
	//const size_t csize = strlen(processInfo->szExeFile) + 1;
	//wchar_t* wexefile = new wchar_t[csize];
	//mbstowcs_s(NULL, wexefile, csize, processInfo->szExeFile, _TRUNCATE);

	int size = WideCharToMultiByte(CP_ACP, 0, processInfo->szExeFile, -1, NULL, 0, NULL, NULL);
	char *ch = new char[size + 1];
	if (WideCharToMultiByte(CP_ACP, 0, processInfo->szExeFile, -1, ch, size, NULL, NULL))
	{
		if (strstr(ch, "app.exe"))
		{
			ID = processInfo->th32ProcessID;
			HANDLE hProcess;
			hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, ID);
			TerminateProcess(hProcess, 0);
			CloseHandle(hProcess);
		}
	}
}
CloseHandle(hSnapShot);
delete processInfo;
processInfo = nullptr;
posted @ 2024-01-08 10:49  YiXiaoKezz  阅读(240)  评论(0编辑  收藏  举报