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

1

16

How can I minimize/maximize windows in macOS from a Python script? On Windows, there's a win32 api (the ShowWindow() function) that can do this. I'd like the macOS equivalent. I'd like to have a script be able to find a window from its title, then minimize or maximize it.

Is this possible? I assume I need to use the pyobjc module for this.

Secede answered 10/11, 2018 at 8:27 Comment(1)
Try this, it might help #25467295 unix.stackexchange.com/questions/385949/…Paternal
S
10

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, NSWorkspace
from Quartz import kCGWindowListOptionOnScreenOnly, kCGNullWindowID, CGWindowListCopyWindowInfo

workspace = 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, NSApplicationActivateAllWindows
app.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

Sike answered 15/8, 2019 at 9:16 Comment(1)
this doesn't do the minimize animation though is there really not another alternative?Galahad

© 2022 - 2024 — McMap. All rights reserved.