简体   繁体   English

Mac Python关闭视窗

[英]Mac Python Close Window

I was wondering if there was a way of watching for a window to open and when it does close it? 我想知道是否有一种方法可以监视打开的窗口以及何时关闭窗口? I've got a very annoying VPN client on our Mac systems that is very verbose and gets really annoying. 我的Mac系统上有一个非常烦人的VPN客户端,它非常冗长且非常烦人。 There's no configuration to change this, so I'm wondering if I could write a Python script that is always running and watching for the window to open and close it? 没有配置可以更改此设置,因此我想知道是否可以编写一个始终运行并监视窗口打开和关闭的Python脚本?

As far as I know, there's no global notification that gets generated every time a window is opened, and no standard notification that every app uses, and no other way to do this in general, short of (a) injecting code into the VPN client, (b) using deprecated functionality like CGRemoteOperation , or (c) reverse engineering undocumented Window Server functionality. 据我所知,每次打开一个窗口时都不会生成全局通知,也没有每个应用程序都使用的标准通知,并且一般来说,没有其他方法可以做到,除非(a)向VPN客户端中注入代码,(b)使用已弃用的功能(例如CGRemoteOperation )或(c)反向工程未记录的Window Server功能。

So, the simplest solution is to periodically poll for windows and close them, probably using UI scripting via ScriptingBridge, NSAppleScript (through pyobjc), or appscript. 因此,最简单的解决方案是定期轮询窗口并关闭它们,可能使用通过ScriptingBridge,NSAppleScript(通过pyobjc)或appscript的UI脚本。

For example: 例如:

se = appscript.app('SystemEvents')
while True:
    try:
        client = se.application_processes['Annoying VPN Client']
        window = client.windows['Annoying Window']
        close = window.buttons[1]
        close.click()
    except Exception as e:
        print('Exception: {}'.format(e))
    time.sleep(1)

If you're interested in the other options—which you won't be able to do from Python—let me know. 如果您对其他选项感兴趣(您将无法使用Python实现),请告诉我。 If you're familiar with system-level C and ObjC programming, creating a SIMBL program that hooks into the ObjC runtime to insert your own delegate in front of the existing one and intercept the relevant messages isn't that hard. 如果您熟悉系统级C和ObjC编程,则创建一个可以连接到ObjC运行时以在现有对象之前插入您自己的委托并拦截相关消息的SIMBL程序并不难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM