关闭exe
#include <filesystem>
#include <Windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <vector>
bool StopProcesses(const std::vector<std::string>& inexePaths)
{
bool result = false;
std::vector<std::string> exePaths = inexePaths;
for (auto exePath : exePaths)
{
std::string inputFileName = std::filesystem::path(exePath).filename().string();
std::replace(exePath.begin(), exePath.end(), '/', '\\');
wchar_t exePathWide[MAX_PATH];
wchar_t exeName[MAX_PATH];
int numChars = MultiByteToWideChar(CP_UTF8, 0, inputFileName.c_str(), -1, exeName, MAX_PATH);
if (numChars == 0) {
std::cout << "Error: failed to convert exeName to wide char format, error code = " << GetLastError() << std::endl;
return false;
}
int numChars_2 = MultiByteToWideChar(CP_UTF8, 0, exePath.c_str(), -1, exePathWide, MAX_PATH);
if (numChars_2 == 0) {
std::cout << "Error: failed to convert exePath to wide char format, error code = " << GetLastError() << std::endl;
return false;
}
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
std::cout << "Error: failed to create process snapshot handle, error code = " << GetLastError() << std::endl;
return false;
}
PROCESSENTRY32W processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32W);
BOOL bFound = Process32FirstW(hSnapshot, &processEntry);
while (bFound) {
if (wcscmp(processEntry.szExeFile, exeName) == 0)
{
TCHAR fullPath[MAX_PATH];
HANDLE tempprocessHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processEntry.th32ProcessID);
if (tempprocessHandle != NULL) {
DWORD size = MAX_PATH;
if (QueryFullProcessImageName(tempprocessHandle, 0, fullPath, &size))
{
if (wcscmp(fullPath, exePathWide) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processEntry.th32ProcessID);
if (hProcess != NULL) {
if (TerminateProcess(hProcess, 0)) {
std::cout << "Success: stopped process " << exePath << std::endl;
result = true;
}
else
{
std::cout << "Error: stopped process " << exePath << std::endl;
std::cout << "Error: failed to terminate process, error code = " << GetLastError() << std::endl;
}
CloseHandle(hProcess);
}
else {
std::cout << "Error: failed to open process handle, error code = " << GetLastError() << std::endl;
}
}
}
CloseHandle(tempprocessHandle);
}
break;
}
bFound = Process32NextW(hSnapshot, &processEntry);
}
CloseHandle(hSnapshot);
if (!result)
{
std::cout << "Error: process " << exePath << " not found" << std::endl;
}
}
return result;
}