我希望我的C ++程序扫描进程,当某个file.exe运行时,我希望我的程序可以执行某些操作(此处无关紧要)。你能帮我完成这个任务吗?
我在互联网上找到了一些东西。这可以吗?
CreateMutex(NULL, FALSE, NAMEofTHEprocess_exe);
if (GetLastError() == ERROR_ALREADY_EXISTS)return 0;
我可以在我的程序中使用它吗?我不知道Mutex是什么。
答案 0 :(得分:2)
以下是Windows中正在运行的进程的基本枚举:
#define WINVER 0x0500
#define _WIN32_WINNT 0x0500
#define PSAPI_VERSION 1
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <sddl.h>
void ListProcesses()
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
::GlobalMemoryStatusEx(&statex);
::EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
cProcesses = cbNeeded / sizeof(DWORD);
for (size_t i = 0; i < cProcesses; ++i)
if(aProcesses[i] != 0)
std::cout << "PID: " << aProcesses[i] << ", Name: " << getProcessNameByID(aProcesses[i]) << std::endl;
}
您可以使用getProcessNameByID
的最终名称查找来做出决定。这是getProcessPathNameByID
的代码:
#include <tchar.h>
std::string getProcessNameByHandle(HANDLE hProcess)
{
if (NULL == hProcess)
return "<unknown>";
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HMODULE hMod;
DWORD cbNeeded;
if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
::GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
return std::string(szProcessName);
}
std::string getProcessNameByID(DWORD processID)
{
HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
std::string result = getProcessNameByHandle(hProcess);
::CloseHandle(hProcess);
return result;
}