0
# Window Management
1
2
Window control and management operations for finding, manipulating, and interacting with application windows. These functions provide comprehensive window management capabilities including finding windows by title, getting window information, and controlling window state and position.
3
4
**Note**: Window management functions are primarily supported on Windows platform. Limited functionality may be available on other platforms.
5
6
## Capabilities
7
8
### Active Window Operations
9
10
Get information about and interact with the currently active (focused) window.
11
12
```python { .api }
13
def getActiveWindow():
14
"""
15
Get the currently active (focused) window.
16
17
Returns:
18
Window: Window object representing the active window, or None if no active window
19
20
Platform: Windows (primary support), limited macOS/Linux support
21
"""
22
23
def getActiveWindowTitle():
24
"""
25
Get the title of the currently active window.
26
27
Returns:
28
str: Title of the active window, or None if no active window
29
30
Platform: Windows (primary support), limited macOS/Linux support
31
"""
32
```
33
34
### Window Discovery
35
36
Find windows by various criteria including title, position, and other attributes.
37
38
```python { .api }
39
def getWindowsAt(x, y):
40
"""
41
Get all windows at the specified screen coordinates.
42
43
Parameters:
44
- x, y (int): Screen coordinates
45
46
Returns:
47
List[Window]: List of Window objects at the specified position
48
49
Platform: Windows only
50
"""
51
52
def getWindowsWithTitle(title):
53
"""
54
Get all windows with the specified title (exact match).
55
56
Parameters:
57
- title (str): Exact window title to match
58
59
Returns:
60
List[Window]: List of Window objects with matching title
61
62
Platform: Windows (primary), limited macOS/Linux support
63
64
Example:
65
notepad_windows = pyautogui.getWindowsWithTitle('Notepad')
66
if notepad_windows:
67
notepad_windows[0].activate()
68
"""
69
70
def getAllWindows():
71
"""
72
Get all visible windows on the desktop.
73
74
Returns:
75
List[Window]: List of all Window objects
76
77
Platform: Windows (primary), limited macOS/Linux support
78
"""
79
80
def getAllTitles():
81
"""
82
Get titles of all visible windows.
83
84
Returns:
85
List[str]: List of window titles
86
87
Platform: Windows (primary), limited macOS/Linux support
88
"""
89
```
90
91
### Window Class
92
93
The Window class provides methods and properties for interacting with individual windows.
94
95
```python { .api }
96
class Window:
97
"""
98
Represents a window on the desktop with methods for manipulation and property access.
99
100
Platform: Windows (full support), limited macOS/Linux support
101
"""
102
103
# Window Properties
104
@property
105
def title(self):
106
"""str: Window title text"""
107
108
@property
109
def left(self):
110
"""int: Left edge X coordinate of window"""
111
112
@property
113
def top(self):
114
"""int: Top edge Y coordinate of window"""
115
116
@property
117
def right(self):
118
"""int: Right edge X coordinate of window"""
119
120
@property
121
def bottom(self):
122
"""int: Bottom edge Y coordinate of window"""
123
124
@property
125
def width(self):
126
"""int: Window width in pixels"""
127
128
@property
129
def height(self):
130
"""int: Window height in pixels"""
131
132
@property
133
def size(self):
134
"""Tuple[int, int]: Window size as (width, height)"""
135
136
@property
137
def topleft(self):
138
"""Tuple[int, int]: Top-left corner as (x, y)"""
139
140
@property
141
def topright(self):
142
"""Tuple[int, int]: Top-right corner as (x, y)"""
143
144
@property
145
def bottomleft(self):
146
"""Tuple[int, int]: Bottom-left corner as (x, y)"""
147
148
@property
149
def bottomright(self):
150
"""Tuple[int, int]: Bottom-right corner as (x, y)"""
151
152
@property
153
def center(self):
154
"""Tuple[int, int]: Window center as (x, y)"""
155
156
@property
157
def box(self):
158
"""Tuple[int, int, int, int]: Window bounds as (left, top, width, height)"""
159
160
@property
161
def area(self):
162
"""int: Window area in pixels (width * height)"""
163
164
@property
165
def isMaximized(self):
166
"""bool: True if window is maximized"""
167
168
@property
169
def isMinimized(self):
170
"""bool: True if window is minimized"""
171
172
@property
173
def isActive(self):
174
"""bool: True if window is currently active/focused"""
175
176
@property
177
def visible(self):
178
"""bool: True if window is visible"""
179
180
# Window Control Methods
181
def activate(self):
182
"""
183
Bring window to front and give it focus.
184
185
Returns:
186
None
187
"""
188
189
def close(self):
190
"""
191
Close the window.
192
193
Returns:
194
None
195
"""
196
197
def minimize(self):
198
"""
199
Minimize the window.
200
201
Returns:
202
None
203
"""
204
205
def maximize(self):
206
"""
207
Maximize the window.
208
209
Returns:
210
None
211
"""
212
213
def restore(self):
214
"""
215
Restore window from minimized or maximized state.
216
217
Returns:
218
None
219
"""
220
221
def resize(self, width, height):
222
"""
223
Resize the window to specified dimensions.
224
225
Parameters:
226
- width, height (int): New window dimensions in pixels
227
228
Returns:
229
None
230
"""
231
232
def resizeRel(self, widthOffset, heightOffset):
233
"""
234
Resize window relative to current size.
235
236
Parameters:
237
- widthOffset, heightOffset (int): Relative size changes in pixels
238
239
Returns:
240
None
241
"""
242
243
def resizeTo(self, width, height):
244
"""Alias for resize() - resize window to absolute dimensions."""
245
246
def moveTo(self, x, y):
247
"""
248
Move window to absolute screen position.
249
250
Parameters:
251
- x, y (int): New top-left corner coordinates
252
253
Returns:
254
None
255
"""
256
257
def moveRel(self, xOffset, yOffset):
258
"""
259
Move window relative to current position.
260
261
Parameters:
262
- xOffset, yOffset (int): Relative movement in pixels
263
264
Returns:
265
None
266
"""
267
```
268
269
## Usage Examples
270
271
```python
272
import pyautogui
273
import time
274
275
# Get active window information
276
active_window = pyautogui.getActiveWindow()
277
if active_window:
278
print(f"Active window: {active_window.title}")
279
print(f"Position: ({active_window.left}, {active_window.top})")
280
print(f"Size: {active_window.width} x {active_window.height}")
281
282
# Find specific application windows
283
notepad_windows = pyautogui.getWindowsWithTitle('Untitled - Notepad')
284
if notepad_windows:
285
notepad = notepad_windows[0]
286
print(f"Found Notepad at: {notepad.topleft}")
287
notepad.activate() # Bring to front
288
else:
289
print("Notepad not found")
290
291
# Work with multiple windows of same application
292
chrome_windows = pyautogui.getWindowsWithTitle('Google Chrome')
293
for i, window in enumerate(chrome_windows):
294
print(f"Chrome window {i+1}: {window.title}")
295
296
# Get all window titles
297
all_titles = pyautogui.getAllTitles()
298
print("All open windows:")
299
for title in all_titles:
300
print(f" - {title}")
301
302
# Window manipulation
303
def organize_windows():
304
"""Organize all windows in a grid pattern"""
305
windows = pyautogui.getAllWindows()
306
screen_width, screen_height = pyautogui.size()
307
308
# Calculate grid dimensions
309
num_windows = len(windows)
310
cols = int(num_windows ** 0.5) + 1
311
rows = (num_windows + cols - 1) // cols
312
313
window_width = screen_width // cols
314
window_height = screen_height // rows
315
316
for i, window in enumerate(windows):
317
if window.visible and not window.isMinimized:
318
col = i % cols
319
row = i // cols
320
321
x = col * window_width
322
y = row * window_height
323
324
window.moveTo(x, y)
325
window.resize(window_width - 10, window_height - 10) # Small gap
326
327
# Window state management
328
def manage_window_state(window_title):
329
"""Demonstrate window state management"""
330
windows = pyautogui.getWindowsWithTitle(window_title)
331
if not windows:
332
print(f"Window '{window_title}' not found")
333
return
334
335
window = windows[0]
336
337
# Show window properties
338
print(f"Window: {window.title}")
339
print(f"Maximized: {window.isMaximized}")
340
print(f"Minimized: {window.isMinimized}")
341
print(f"Active: {window.isActive}")
342
print(f"Visible: {window.visible}")
343
344
# Demonstrate state changes
345
window.activate()
346
time.sleep(1)
347
348
if window.isMaximized:
349
window.restore()
350
time.sleep(1)
351
352
window.maximize()
353
time.sleep(1)
354
355
window.minimize()
356
time.sleep(1)
357
358
window.restore()
359
360
# Find and interact with windows at specific coordinates
361
def click_window_at_position(x, y):
362
"""Find and activate window at screen coordinates"""
363
windows_at_pos = pyautogui.getWindowsAt(x, y)
364
if windows_at_pos:
365
top_window = windows_at_pos[0] # Get topmost window
366
print(f"Found window at ({x}, {y}): {top_window.title}")
367
top_window.activate()
368
return top_window
369
else:
370
print(f"No window found at ({x}, {y})")
371
return None
372
373
# Advanced window searching
374
def find_window_by_partial_title(partial_title):
375
"""Find windows with titles containing the specified text"""
376
all_windows = pyautogui.getAllWindows()
377
matching_windows = []
378
379
for window in all_windows:
380
if partial_title.lower() in window.title.lower():
381
matching_windows.append(window)
382
383
return matching_windows
384
385
# Example usage
386
chrome_windows = find_window_by_partial_title('Chrome')
387
for window in chrome_windows:
388
print(f"Found Chrome window: {window.title}")
389
390
# Window positioning and sizing
391
def center_window(window_title, width=800, height=600):
392
"""Center a window on screen with specified size"""
393
windows = pyautogui.getWindowsWithTitle(window_title)
394
if not windows:
395
return False
396
397
window = windows[0]
398
screen_width, screen_height = pyautogui.size()
399
400
# Calculate center position
401
x = (screen_width - width) // 2
402
y = (screen_height - height) // 2
403
404
window.moveTo(x, y)
405
window.resize(width, height)
406
window.activate()
407
return True
408
409
# Use the function
410
if center_window('Calculator', 400, 500):
411
print("Calculator centered successfully")
412
else:
413
print("Calculator window not found")
414
415
# Monitor window changes
416
def monitor_active_window(duration=10):
417
"""Monitor active window changes for specified duration"""
418
print(f"Monitoring active window for {duration} seconds...")
419
last_title = ""
420
start_time = time.time()
421
422
while time.time() - start_time < duration:
423
current_title = pyautogui.getActiveWindowTitle()
424
if current_title != last_title:
425
print(f"Active window changed to: {current_title}")
426
last_title = current_title
427
time.sleep(0.5)
428
429
# Run monitoring
430
monitor_active_window(30)
431
```
432
433
## Platform-Specific Notes
434
435
### Windows
436
- Full functionality available
437
- Uses PyGetWindow library for comprehensive window management
438
- Supports all window properties and methods
439
- Works with all window types including system dialogs
440
441
### macOS
442
- Limited functionality through PyObjC
443
- Basic window detection and activation
444
- Some properties may not be available
445
- Performance may be slower than Windows
446
447
### Linux
448
- Basic functionality through X11
449
- Window detection and simple operations
450
- Advanced features may not work consistently
451
- Depends on window manager capabilities
452
453
## Error Handling
454
455
```python
456
# Safe window operations with error handling
457
def safe_window_operation(window_title, operation):
458
"""Safely perform window operations with error handling"""
459
try:
460
windows = pyautogui.getWindowsWithTitle(window_title)
461
if not windows:
462
print(f"Window '{window_title}' not found")
463
return False
464
465
window = windows[0]
466
467
if operation == 'activate':
468
window.activate()
469
elif operation == 'maximize':
470
window.maximize()
471
elif operation == 'minimize':
472
window.minimize()
473
elif operation == 'close':
474
window.close()
475
476
return True
477
478
except Exception as e:
479
print(f"Error performing {operation} on {window_title}: {e}")
480
return False
481
482
# Use safe operations
483
safe_window_operation('Notepad', 'activate')
484
safe_window_operation('Calculator', 'maximize')
485
```
486
487
## Dependencies
488
489
Window management functionality requires the PyGetWindow library:
490
491
```bash
492
pip install pygetwindow
493
```
494
495
This dependency is automatically installed with PyAutoGUI on Windows but may need separate installation on other platforms.