Getting Process Handle by Name in C
To obtain the handle of a process based on its process name, such as "example.exe," we can utilize the following approach in C .
The first step is to create a snapshot of all running processes using the CreateToolhelp32Snapshot function:
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Next, we need to iterate through the processes in the snapshot to find the one with the specified name:
PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { // Found the process
With the process information in hand, we can use the OpenProcess function to obtain its handle:
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
Note: To use the PROCESS_ALL_ACCESS privilege, you may need to enable the debug privilege, as shown in the alternative code snippet provided in the question's answer.
EnableDebugPriv();
Once you have the process handle, you can perform various operations on it, including terminating the process using TerminateProcess.
TerminateProcess(hProcess, 0);
The above is the detailed content of How Can I Get a Process Handle by Name in C ?. For more information, please follow other related articles on the PHP Chinese website!