Alsors
Alsors

Reputation: 1

How to retrieve the full path for the foreground window in Windows 10 using the Python ctypes module?

I've decided to bite more than I could chew here. I've spent the past day attempting this through trial and error however I have yet to figure out the correct way to interact with the Windows API.

I would like to retrieve the full path for the focused window on my Windows 10 PC using Python. So far I have hot glued this together:

from ctypes import *
import sys
import time

try:
    while True:
        # Retrieve the handle for the foreground window
        hwnd = windll.user32.GetForegroundWindow()
        # Create a buffer for the GetWindowThreadProcessId function
        buffer = create_string_buffer(260)
        # Retrieve the full path and file name of the foreground window
        windll.user32.GetWindowModuleFileName(hwnd, buffer, sizeof(buffer))
        # Print the full path and file name of the foreground window
        print(buffer.value)
        # Sleep for 100 milliseconds
        time.sleep(0.1)
except KeyboardInterrupt:
    sys.exit(0)

Unfortunatly this doesn't have my desired output. When I have Command Prompt open I would expect the path to be C:\Windows\system32\cmd.exe however I get C:\Users\John\AppData\Local\Programs\Python\Python39\python.exe instead. When I open any other window I get an empty output.

Upvotes: 0

Views: 538

Answers (1)

Zeus
Zeus

Reputation: 3890

GetWindowModuleFileName calls GetModuleFileName from which the MSDN doc says :

The module must have been loaded by the current process.

So you can't get the full path you want directly by calling GetWindowModuleFileName.

You can refer to this thread : How to get the Executable name of a window.

And here is an example implemented in C++, you can refer to it:

#include <Windows.h>
#include <psapi.h>
#include <iostream>
#include <tlhelp32.h>
BOOL SetPrivilege(HANDLE hToken, LPCTSTR Privilege,BOOL bEnablePrivilege)
{
    TOKEN_PRIVILEGES tp = { 0 };
    // Initialize everything to zero 
    LUID luid;
    DWORD cb = sizeof(TOKEN_PRIVILEGES);
    if (!LookupPrivilegeValue(NULL, Privilege, &luid))
    {
        return FALSE;
    }
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege) {
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    }
    else {
        tp.Privileges[0].Attributes = 0;
    }
    AdjustTokenPrivileges(hToken, FALSE, &tp, cb, NULL, NULL);
    if (GetLastError() != ERROR_SUCCESS)
    {
        std::cout << "err = " << GetLastError() << std::endl;
        return FALSE;
    }

    return TRUE;
}
int main()
{
    HANDLE curHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
    OpenProcessToken(curHandle, TOKEN_ADJUST_PRIVILEGES, &curHandle);
    SetPrivilege(curHandle, SE_DEBUG_NAME, TRUE);
    while (1)
    {
        TCHAR buf[MAX_PATH] = L"";
        HWND hwnd = GetForegroundWindow();
        DWORD pid = 0;
        GetWindowThreadProcessId(hwnd, &pid);
        HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
        if (handle)
        {
            GetModuleFileNameEx(handle, 0, buf, MAX_PATH);
            std::wcout << buf << std::endl;
        }
        else
        {
            std::cout << "error = " << GetLastError() << std::endl;
        }
        if (handle) CloseHandle(handle);
        Sleep(100);
    }
    return 0;
}

Upvotes: 1

Related Questions