如何在python中处理“Quit”事件

2024-09-26 22:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检测用户何时在dock菜单中按了“quit”。在

我的应用程序实际上只是一个web界面后端服务器的启动程序。我通过手动等待启动的进程结束(使用轮询和睡眠)将其保存在dock菜单中。ACTIVITY监视器显示它是没有响应,所以我添加了一个本地函数来处理诸如“touch”之类的事件。Not responding标志现在不存在了,但是用户不能退出这个应用程序(我想是因为本机函数处理事件)。在

我用ctypes来访问这个本机函数。在

TVB = subprocess.popen(args)
coreFoundation = cdll.LoadLibrary('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')

CFRunLoopRunInMode = coreFoundation.CFRunLoopRunInMode                  # the native function
CFRunLoopRunInMode.restype = c_int32                                    # its return type
CFRunLoopRunInMode.argtypes = [ c_void_p, c_double, c_bool ]            # its arguments types

defaultMode = c_void_p.in_dll(coreFoundation, u'kCFRunLoopDefaultMode') # the default mode to process events
sleepTime = c_double(5)                                                 # the duration to process the events
retAfterSourceHandled = c_bool(0)                                       # do NOT return after processing

while not TVB.poll():                                                   # keep alive as long as TVB is alive
    CFRunLoopRunInMode(defaultMode, sleepTime, retAfterSourceHandled)
    sleep(5)
    #detect 'quit' here and stop TVB, then quit

我还将考虑CFRunLoopRunInMode的其他解决方案。。。像processNextEvent()这样的东西是理想的。在


Tags: the函数用户应用程序return菜单quitits
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:16

这个问题的一个可能的解决方案是使用PyObjC和一个自定义的UIApplicationDelegate实现。在

    import AppKit
    import Foundation
    from PyObjCTools import AppHelper

    class ApplicationDelegate(Foundation.NSObject):
        """ MAC OS UI specific Delegate class """

        def applicationDidFinishLaunching_(self, notification):
            """ Here you could register a timer to pull your sub-processes, for example. """
            pass

        def applicationWillTerminate_(self, notification):
            """ This is the hook you get for when the user clicks QUIT in dock """
            pass

    app = AppKit.NSApplication.sharedApplication()
    delegate = ApplicationDelegate.alloc().init()
    app.setDelegate_(delegate)
    AppHelper.runEventLoop()

最后,PyObjC与您尝试的ctypes加载没有太大区别,但是它有一些helper方法(比如AppKit.NSRunLoop.currentRunLoop(),或AppHelper.stopEventLoop())可以使python代码更清晰。在

对于这个解决方案,我假设有一个Python项目进一步打包,以便与py2app一起部署。我使用的是pyobjcversion2.3(在macosx10.7.5上的python2.7中使用easy_install安装)。在

相关问题 更多 >

    热门问题