我决定在这里吃得太多了。在过去的一天里,我一直在反复尝试,但是我还没有找到与Windows API交互的正确方式。
我想使用Python在我的Windows10 PC上检索聚焦窗口的完整路径。到目前为止,我已经热粘合在一起了:
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)不幸的是,这没有我想要的输出。当我打开命令提示符时,我希望路径是C:\Windows\system32\cmd.exe,但我得到的却是C:\Users\John\AppData\Local\Programs\Python\Python39\python.exe。当我打开任何其他窗口时,我得到一个空的输出。
发布于 2021-02-16 14:25:43
GetWindowModuleFileName调用GetModuleFileName,MSDN文档说:
模块必须已由当前进程加载。
因此,您不能直接通过调用GetWindowModuleFileName来获取所需的完整路径。
你可以参考这个帖子:How to get the Executable name of a window。
下面是一个用C++实现的例子,你可以参考它:
#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;
}https://stackoverflow.com/questions/66217809
复制相似问题