Skip to content

Instantly share code, notes, and snippets.

@3735943886
Last active August 4, 2023 17:27
Show Gist options
  • Save 3735943886/72c42a24aa39938b302b67b86f1aec31 to your computer and use it in GitHub Desktop.
Save 3735943886/72c42a24aa39938b302b67b86f1aec31 to your computer and use it in GitHub Desktop.
#pragma comment(lib, "user32")
#pragma comment(lib, "psapi")
 
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
 
void main()
{
    HWND hWnd;
    DWORD dwPid;
    HANDLE hProc;
    CHAR FileName[MAX_PATH];
 
    /* Get HWND of target window. */
    if(hWnd = FindWindow(TEXT("Notepad"), NULL))
    {
        printf("Hwnd : 0x%016X\n", hWnd);
 
        /* Get Pid from HWND with GetWindowThreadProcessId. */
        if(GetWindowThreadProcessId(hWnd, &dwPid))
        {
            printf("Pid : 0x%08X\n", dwPid);
 
            /*
             * Open Handle with OpenProcess
             * The handle must have the PROCESS_QUERY_INFORMATION
             * and PROCESS_VM_READ access rights to get file name.
             */
            if(hProc = OpenProcess(PROCESS_QUERY_INFORMATION
                | PROCESS_VM_READ, FALSE, dwPid))
            {
                printf("Handle : 0x%016X\n", hProc);
 
                /*
                 * Retrieves the fully qualified path for the file containing
                 * the specified window.
                 * Path portion can be removed with PathStripPath.
                 */
                if(GetModuleFileNameExA(hProc, NULL, FileName, MAX_PATH))
                {
                    printf("File name : %s\n", FileName);
                }
 
                /* Closes an open object handle. */
                CloseHandle(hProc);
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment