Home > Backend Development > C++ > body text

How Can I Get a Process Handle by Name in C ?

Barbara Streisand
Release: 2024-11-21 16:01:10
Original
562 people have browsed it

How Can I Get a Process Handle by Name in C  ?

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);
Copy after login

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
Copy after login

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);
Copy after login

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();
Copy after login

Once you have the process handle, you can perform various operations on it, including terminating the process using TerminateProcess.

TerminateProcess(hProcess, 0);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template