#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

int main( int, char *[] )
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken); 
}

int main( int, char *[] )
{
    EnableDebugPriv();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}
Answer from xian on Stack Overflow
Top answer
1 of 7
99
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

int main( int, char *[] )
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}

Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken); 
}

int main( int, char *[] )
{
    EnableDebugPriv();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "target.exe") == 0)
            {  
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);

                // Do stuff..

                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);

    return 0;
}
2 of 7
17

There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses, OpenProcess, EnumProcessModules, and GetModuleBaseName.

The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot to get a snapshot of the process list, walk over it with Process32First and Process32Next, which provides module name and process ID, until you find the one you want, and then call OpenProcess to get a handle.

๐ŸŒ
Al Jensen's Programming
aljensencprogramming.wordpress.com โ€บ tag โ€บ getcurrentprocess
GetCurrentProcess() โ€“ C Programming with Al Jensen
July 15, 2015 - The GetCurrentProcess() function returns a pseudo handle to the current process. A handle is typically an integer value, although technically speaking we ought to consider a handle as opaque, meaning that we only really need to focus on how to us it, not what it is, as such.
Discussions

C Getting handle from process without OpenProcess
Hi i was wondering how could i get specific handle from process. I mean i have dll what i inject into process for example. "example.exe" whi More on unknowncheats.me
๐ŸŒ unknowncheats.me
August 2, 2016
[Help]Get a list of Handles of a process - C++ Forum
I need to know if the handle exists. I don't understand fully what this handle list means. I created this application, and I didn't open any of these handles. I'm assuming that these handles were created in Kernel/Low level functions, for basic process functionality. More on cplusplus.com
๐ŸŒ cplusplus.com
c - Get the process handle of a process by image name - Stack Overflow
I need the simplest way from C using Win32 to get the process handle of another process by its executable file name. The process I am looking for does not have any registered window classes. I also More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 17, 2011
c++ - how to get process handle from process id? - Stack Overflow
I have process Id , I want to get its process handle. Is there any API available for that. I tried to use OpenProcess but it returns NULL, and GetLastError =0. This I am trying on Vista. I gues... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ windows โ€บ win32 โ€บ api โ€บ processthreadsapi โ€บ nf-processthreadsapi-getcurrentprocess
GetCurrentProcess function (processthreadsapi.h) - Win32 apps | Microsoft Learn
February 22, 2024 - A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this constant value. The calling process can use a pseudo handle to specify ...
๐ŸŒ
UnKnoWnCheaTs
unknowncheats.me โ€บ forum โ€บ c-and-c- โ€บ 183973-getting-handle-process-openprocess.html
[Help] C++ Getting handle from process without OpenProcess()
August 2, 2016 - Hi i was wondering how could i get specific handle from process. I mean i have dll what i inject into process for example. "example.exe" whi
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ windows โ€บ 95774
[Help]Get a list of Handles of a process - C++ Forum
(I'm using Olly Debugger) How would I check for an existing handle, and then check the name(HKEY_LOCAL_MACHINE\SYSTEM\etc.)? This is going to be done inside of itself, not inside of another process. I've so far only found a way to get the number of handles in a process.
Top answer
1 of 1
2

Use CreateToolhelp32Snapshot, Process32First, and Process32Next to enumerate all of the processes.

Inside the PROCESSENTRY32 you can find a szExeFile member. You can get the process handle by calling OpenProcess with the process ID th32ProcessID within the same struct.

Once you find a process matching your exe name, you can break out of your loop and obtain the handle.

Note: If you need to enumerate EVERY process no matter what the session is, you should acquire the SE_DEBUG privilege.

At the top of your main call this:

acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege

And here is the definition of acquirePrivilegeByName:

BOOL acquirePrivilegeByName(
                            const TCHAR     *szPrivilegeName)
{
    HANDLE          htoken;
    TOKEN_PRIVILEGES    tkp;
    DWORD           dwerr;

    if (szPrivilegeName == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid)))
        return FALSE;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken))
        return FALSE;

    if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) ||
        GetLastError() != ERROR_SUCCESS)    // may equal ERROR_NOT_ALL_ASSIGNED
    {
        dwerr = GetLastError();
        CloseHandle(htoken);
        SetLastError(dwerr);
        return FALSE;
    }

    CloseHandle(htoken);
    SetLastError(ERROR_SUCCESS);

    return TRUE;
} //acquirePrivilegeByName()

In addition to what I said above, there is an example on how to use the above Win32 API here.

Find elsewhere
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ windows โ€บ 60481
Writeing a program to end others - C++ Forum
EnumProcesses() fills an array with process ID's. You can use those process ID's with OpenProcess() to obtain the process handle. With that handle you can terminate the process using TerminateProcess(). Of course that you don't want to terminate all processes and I guess you'll differentiate by process name (the name of the executable).
๐ŸŒ
Al Jensen's Programming
aljensencprogramming.wordpress.com โ€บ tag โ€บ createprocess
CreateProcess() โ€“ C Programming with Al Jensen
A process is created via a call to the CreateProcess() function, and remains in existence until all open handles to the process have been closed, at which point the reference count for the process object is zero, and there are no more active threads in the process. The GetCurrentProcess() function returns a pseudo handle to the current process.
๐ŸŒ
CodeProject
codeproject.com โ€บ articles โ€บ How-to-get-handle-to-any-running-process-by-its-na
Coding Education Platforms for Beginners | .Software
The rise of coding education platforms reflects the growing demand for tech-literate individuals across all industries. By centering the learning process around interactivity, these platforms cater to a range of learning styles, offering realistic practice that textbooks cannot.
๐ŸŒ
GitHub
gist.github.com โ€บ hpcx82 โ€บ 902894
Get process handle by its name in Windows ยท GitHub
Save hpcx82/902894 to your computer and use it in GitHub Desktop. Download ZIP ยท Get process handle by its name in Windows ยท Raw ยท GetProcessName.cc ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
๐ŸŒ
DEV Community
dev.to โ€บ tbhaxor โ€บ windows-system-programming-processes-1hg7
Windows System Programming: Processes - DEV Community
September 11, 2020 - If function will run successfully, it will return you a valid process handle. To get the name of executable, you need to enumerate the process modules and then get the base module name ยท A loadable module of the process that let's process function is known as process module. It can either be ...
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sysinternals โ€บ downloads โ€บ handle
Handle - Sysinternals | Microsoft Learn
When not in search mode (enabled by specifying a name fragment as a parameter), Handle divides its output into sections for each process it is printing handle information for. Dashed lines are used as a separator, immediately below which you will see the process name and its process id (PID).
๐ŸŒ
Pavel Yosifovich
scorpiosoftware.net โ€บ 2020 โ€บ 03 โ€บ 15 โ€บ how-can-i-close-a-handle-in-another-process
How can I close a handle in another process? โ€“ Pavel Yosifovich
March 15, 2020 - If we want to achieve this programmatically, we have to locate the handle first. Unfortunately, the documented Windows API does not provide a way to enumerate handles, not even in the current process. We have to go with the (officially undocumented) Native API if we want to enumerate handles.
๐ŸŒ
Bilimedtech
labs.bilimedtech.com โ€บ operating-systems โ€บ 6 โ€บ index.html
6: Creating a Process in C โ€” BilimEdtech Labs documentation
CreateProcess() requires several important parameters. The full path to the application or program to execute. Pointer to STARTUPINFO struct. ... You must allocate the memory required for the struct. Pointer to PROCESS_INFORMATION struct.