Reputation: 773
Using pyautogui is there a way to get a handle to a window so that I can ensure that a click is performed on that window only? In other words, if my window isn't in focus, then the click does not occur. Additionally, if my window isn't in focus then I bring it into focus and then perform the actions.
The way to identify a window could be an ID, window title etc similar to this https://autohotkey.com/docs/commands/WinGet.htm
Is there any other Python module that supports this kind of functionality?
Upvotes: 30
Views: 100935
Reputation: 35374
Working for me with pygetwindow
pygetwindow.getWindowsWithTitle(title='Stack Overflow')[0] .activate()
Upvotes: 0
Reputation: 451
This code might help to get what window you want to minimize or maximize. Example: If you want to get a Chrome window titled "Stack Overflow",
pyautogui.getWindowsWithTitle("Stack Overflow")[0].minimize()
Or if you want to minimize or maximize any file explorer window that titled "music", the same thing applies.
pyautogui.getWindowsWithTitle("music")[0].maximize()
If you are not sure about which window you require, you can get a list using this
Note, must call pyautogui.getWindowsWithTitle()
, dont call as
from pyautogui import getWindowsWithTitle
getWindowsWithTitle() # will raise error
Upvotes: 22
Reputation: 676
A hybrid pyautogui/win32gui solution for Windows:
import pyautogui
import win32gui
import time
window = pyautogui.getWindowsWithTitle("Your Window Title")[0]
rect = window._rect
if rect.x == -32000 or rect.y == -32000: # minimized check
window.restore()
time.sleep(1) # if restoring, need to wait briefly to set to foreground
win32gui.SetForegroundWindow(window._hWnd)
Upvotes: 0
Reputation: 1
In order to use pyautogui on app pages that are already maximized but not in focus First Minimize ten Maximize:
pyautogui.getWindowsWithTitle("FileZilla")[0].minimize()
pyautogui.getWindowsWithTitle("FileZilla")[0].maximize()
Upvotes: 0
Reputation:
Is there any other Python module that supports this kind of functionality?
https://github.com/pywinauto/pywinauto
https://pywinauto.readthedocs.io/en/latest/#some-similar-tools-for-comparison lists as other similar Python tools:
Upvotes: 8
Reputation: 1830
PyAutoGui itself says, in its documentation's FAQ section,
Q: Can PyAutoGUI figure out where windows are or which windows are visible? Can it focus, maximize, minimize windows? Can it read the window titles?
A: Unfortunately not, but these are the next features planned for PyAutoGUI. This functionality is being implemented in a Python package named PyGetWindow, which will be included in PyAutoGUI when complete.
Now, if you go on over to PyGetWindow's repo, you'll see there's no code there yet, but there is a random_notes.txt file, with this pointer:
Finding window titles on Windows:
http://stackoverflow.com/questions/37501191/how-to-get-windows-window-names-with-ctypes-in-python
which has some interesting information. (I haven't tried it yet.)
Upvotes: 14