我如何在 macOS 中使用 Python 脚本中的 Cocoa API minimize/maximize windows?

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

如何从 Python 脚本在 macOS 中 minimize/maximize windows? 在 Windows 上,有一个 win32 api(ShowWindow() 函数)可以做到这一点。我想要 macOS 等价物。我想让脚本能够从标题中找到 window,然后将其最小化或最大化。

这可能吗?我想我需要为此使用 pyobjc 模块。

可能有不同的方法,其中一种是枚举 运行 应用程序,另一种是枚举应用程序内部的 windows。

我将在这里展示应用方法

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

这将找到当前关注的应用程序,您可以根据标题或任何您想要的更改逻辑

找到app后。您可以使用

将其最小化
app.hide()

您可以使用

再次显示该应用
from Cocoa import NSApplicationActivateIgnoringOtherApps, NSApplicationActivateAllWindows
app.unhide()
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)

# or 
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps | NSApplicationActivateAllWindows)

我必须参考很多线程才能找到这个解决方案

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