如何通过Python脚本最小化/最大化macOS中的窗口?

时间:2018-11-10 08:27:08

标签: python macos pyobjc

如何通过Python脚本最小化/最大化macOS中的窗口?在Windows上,有一个win32 api(ShowWindow()函数)可以做到这一点。我想要等效的macOS。我希望脚本能够从其标题中找到一个窗口,然后将其最小化或最大化。

这可能吗?我认为我需要为此使用pyobjc。

1 个答案:

答案 0 :(得分:6)

可能有不同的方法,其中一种是通过枚举正在运行的应用程序,然后是枚举该应用程序内的窗口。

我将在此处展示应用方法

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