#include <windows.h>
#include <Tlhelp32.h>
#include <sstream>
// 根据进程名称获取进程ID
DWORD GetProcessIDByName(const TCHAR* pName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
{
if (wcscmp(pe.szExeFile, pName) == 0)
{
CloseHandle(hSnapshot);
return pe.th32ProcessID;
}
//printf("%-6d %s\n", pe.th32ProcessID, pe.szExeFile);
}
CloseHandle(hSnapshot);
return 0;
}
// 杀进程
bool KillPro(const TCHAR* szProcName)
{
DWORD dwProcessId = GetProcessIDByName(szProcName);
if (dwProcessId < 0)
{
return false;
}
std::wostringstream oss;
oss.str(_T(""));
oss << _T("/PID ");
oss << dwProcessId;
std::wstring strCmd = oss.str();
ShellExecute(NULL, _T("open"), _T("taskkill.exe"), strCmd.c_str(), _T(""), SW_HIDE);
DWORD dError = ::GetLastError();
if (ERROR_SUCCESS != dError)
{
return false;
}
return true;
}
int main()
{
bool bRet = KillPro(_T("depends_chs.exe"));
return 0;
}