How can I minimize/maximize windows in macOS with the Cocoa API from a Python script? How can I minimize/maximize windows in macOS with the Cocoa API from a Python script? python python

How can I minimize/maximize windows in macOS with the Cocoa API from a Python script?


There are probably different ways to do it, out of which one is by enumerating the running applications and next is enumerating the windows inside the application.

I will show the app approach here

from AppKit import NSApplication, NSApp, NSWorkspacefrom Quartz import kCGWindowListOptionOnScreenOnly, kCGNullWindowID, CGWindowListCopyWindowInfoworkspace = NSWorkspace.sharedWorkspace()activeApps = workspace.runningApplications()for app in activeApps:    if app.isActive():        options = kCGWindowListOptionOnScreenOnly        windowList = CGWindowListCopyWindowInfo(options,                                                kCGNullWindowID)        for window in windowList:            if window['kCGWindowOwnerName'] == app.localizedName():                print(window.getKeys_)                break        break

This will find the current focused app, you can change the logic based on titles or whatever you want

After the app is found. You can minimize it using

app.hide()

And you can show the app again using

from Cocoa import NSApplicationActivateIgnoringOtherApps, NSApplicationActivateAllWindowsapp.unhide()app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)# or app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps | NSApplicationActivateAllWindows)

Lot of threads I had to refer to get to this solution

OS X: Move window from Python

How to list all windows from all workspaces in Python on Mac?

How to get Window reference (CGWindow, NSWindow or WindowRef) from CGWindowID in Swift?

"No such file: 'requirements.txt' error" while installing Quartz module

How to build Apple's Son of grab example?

How to get another application window's title, position and size in Mac OS without Accessibility API?

Get the title of the current active Window/Document in Mac OS X

-[NSRunningApplication activateWithOptions:] not working

How to start an app in the foreground on Mac OS X with Python?

set NSWindow focused

Activate a window using its Window ID