Obtain Active Window Using Python

Getting the name of the active window

From daniweb

  import win32gui
w=win32gui
w.GetWindowText (w.GetForegroundWindow())

How to remember currently active window and then make it focused when needed?

Well,In windows,you can use win32gui.GetForegroundWindow() to save the hwnd of window.(Use pywin32 module).

import win32gui

window_hwnd = win32gui.GetForegroundWindow() # this will return a number(the hwnd of active window when it is running)

To make it active:

win32gui.SetForegroundWindow(window_hwnd)

If you want to get the hwnd of tkinter,you can use

int(root.frame(),16) # root is a Tk() or Toplevel()

Change the active Window

I think the object method you're after is activate:

>>> help(win.activate)
Help on method activate in module
pygetwindow._pygetwindow_win:

activate() method of
pygetwindow._pygetwindow_win.Win32Window instance
Activate this window and make it the foreground window.

So changing your code as follows should work.

import pygetwindow as gw

win = gw.getWindowsWithTitle('Photoshop')[0]
win.activate()


Related Topics



Leave a reply



Submit