如何在Python中获取焦点窗口的目录位置

问题描述 投票:0回答:2

我想知道如何获取当前焦点窗口的路径。

我正在编写一个正在等待特定组合键的脚本,当按下该组合键时,我希望脚本获得焦点窗口的路径。

这就是我现在所拥有的。

获取焦点窗口的名称:

from win32gui import GetForegroundWindow, GetWindowText

print(GetWindowText(GetForegroundWindow()))

这将返回打开的文件夹的名称:

TestFolder

但是我如何获取该文件夹的路径呢?例如,该文件夹位于我的桌面上。

测试文件夹 -- D:\GM\系统文件夹\桌面\测试文件夹

如何通过 Python 代码获取该位置?

python windows directory path filepath
2个回答
0
投票

我不清楚您是在询问任何进程的 .exe 路径,还是在询问文件资源管理器窗口导航到的路径。

任何.exe:

  1. 调用
    GetForegroundWindow
    获取窗口句柄。
  2. 调用
    GetWindowThreadProcessId
    获取拥有该窗口的进程的进程 ID。
  3. 调用
    OpenProcess
    打开进程的句柄。
  4. 拨打
    QueryFullProcessImageName
    获取路径。
  5. CloseHandle
    关闭手柄。

要获取资源管理器窗口导航到的路径,您必须使用

IShellWindows
COM 接口枚举打开的窗口,并使用返回的浏览器接口获取每个窗口的窗口句柄,并将其与
GetForegroundWindow
进行比较。可以在here找到 C++ 枚举示例。该博客文章还展示了如何从浏览器对象获取路径。


0
投票

我们可以遍历所有资源管理器窗口并查找是否有一个在前台,如果有,则获取其路径。
感谢这个答案,我添加了一些小细节:https://stackoverflow.com/a/73181850/8582902

from win32gui import GetForegroundWindow
from win32com import client
from urllib.parse import unquote
from pythoncom import CoInitialize

fore_window_hwnd = GetForegroundWindow()
CoInitialize()
shell = client.Dispatch("Shell.Application")
fore_window_path = None
for window in shell.Windows():
    if window.hwnd != fore_window_hwnd: continue
    fore_window_path = unquote(window.LocationURL[len("file:///"):])
    break
if fore_window_path: msg = f'Path of the foreground window: {fore_window_path}'
else: msg = 'Could not find an explorer window that is in foregroud.'
© www.soinside.com 2019 - 2024. All rights reserved.