1

I would like to know how to get the path of the current window which is in focus.

I am writing a script which is waiting for a specific key-combination and when that combination is pressed, I would like the script to get the path of the window in focus.

This is what I have for now.

To get the name of the window in focus:

from win32gui import GetForegroundWindow, GetWindowText

print(GetWindowText(GetForegroundWindow()))

This returns the name of the folder that is open: TestFolder

But how do I get the path of that folder? For instance, that folder in question is on my desktop.

TestFolder -- D:\GM\System Folders\Desktop\TestFolder

How do I get that location through code in Python?

G.M.
  • 56
  • 5

2 Answers2

0

It is unclear to me if you are asking about the .exe path of any process or if you are asking about the path a File Explorer window has navigated to.

Any .exe:

  1. Call GetForegroundWindow to get the window handle.
  2. Call GetWindowThreadProcessId to get the process id of the process that owns the window.
  3. Call OpenProcess to open a handle to the process.
  4. Call QueryFullProcessImageName to get the path.
  5. Close the handle with CloseHandle.

To get the path a Explorer window has navigated to you must use the IShellWindows COM interface to enumerate the open windows and use the returned browser interface to get the window handle for each window and compare that with GetForegroundWindow. A C++ example of enumerating can be found here. That blog post also shows how you get the path from the browser object.

Anders
  • 97,548
  • 12
  • 110
  • 164
  • 1
    I am asking for the 'path a File Explorer Window' is currently on. Suppose, the current focus is on windows explorer and it is showing "D:\GM\System Folders\Desktop\TestFolder", I would like to know how can I get it via code in python. I am new to this so can't really understand C++ yet. Examples in python would be highly appreciated. – G.M. Jan 16 '22 at 03:26
0

We can iterate over all the Explorer windows and find if there is one in foreground, and if so, get its path.
Thanks to this answer to which I've added minor details: 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.'
manisar
  • 103
  • 1
  • 7