获取所有进程信息:
vector<ProcessInfo>& ProcessHelper::GetProcessInfos()
{
DWORD processes[1024];
DWORD cbNeeded, cProcesses;
BOOL B = EnumProcesses(processes, 1024 * sizeof(DWORD), &cbNeeded);
cProcesses = cbNeeded / sizeof(DWORD);
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
vector<ProcessInfo> * l = new vector<ProcessInfo>();
l->reserve(cProcesses);
unique_ptr<map<int, HWND>> m = ProcessHelper::GetAllProcessHwndMap();
for (int i = 0; i < cProcesses; i++)
{
DWORD processId = processes[i];
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
if (hProcess != NULL)
{
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
auto iter = m->find(processId);
HWND handle = (iter != m->end()) ? iter->second : 0;
l->push_back(ProcessInfo(szProcessName, processId, handle));
CloseHandle(hProcess);
}
}
}
l->shrink_to_fit();
return *l;
}启动一个进程:
bool ProcessHelper::StartProcess(const string& name)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
int len = MultiByteToWideChar(CP_ACP, 0, name.c_str(), -1, NULL, 0);
wchar_t * processName = new wchar_t[len + 1];
MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, processName, len);
BOOL status = CreateProcessW(processName,
NULL,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&pi);
if (status)
{
DWORD r = WaitForInputIdle(pi.hProcess, 5000);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
delete[] processName;
return true;
}
else
{
std::cout << "创建进程:" << name << "失败:" << GetLastError() << std::endl;
delete[] processName;
return false;
}
}杀死一个进程:
bool ProcessHelper::KillProcess(const string& name)
{
vector<ProcessInfo>& processList = FindExe(name);
for (auto iter = processList.begin(); iter != processList.end(); iter++)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, iter->id());
if (hProcess)
{
BOOL status = TerminateProcess(hProcess, 0);
if (status)
{
return true;
}
else
{
std::cout << "终止进程失败: " << GetLastError() << std::endl;
}
}
else
{
std::cout << "获取句柄失败:" << hProcess << std::endl;
return false;
}
}
}