Search code examples
pythonmacoscocoapyobjc

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


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.


Solution

  • 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