如何在macosx上的Python.app中实现全局热键?

2024-09-29 17:47:58 发布

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

我目前正在修改一个应用程序,该应用程序是由我组织内的某个人编写的,但该应用程序已无法维护。我正在尝试实现一个系统范围的全局热键,它只会在按下时使应用程序窗口成为焦点。在

我在网上看到的唯一实现是通过PyObjC在他们的hotkeypthon示例中实现的。不过,这个例子使用的是碳元素,在我测试它的时候,它似乎根本就不起作用。在

以下是我所尝试的,但似乎行不通:

from Foundation import *
from AppKit import *
from Carbon.CarbonEvt import RegisterEventHotKey
from Carbon.Events import cmdKey, controlKey, optionKey, shiftKey
import objc, AppLauncher
import platform
import struct
IS_SNOW_LEOPARD = platform.mac_ver()[0].startswith('10.6')
if IS_SNOW_LEOPARD:
  from Quartz import *

kEventHotKeyPressedSubtype = 6
kEventHotKeyReleasedSubtype = 9


class AppLauncher(NSObject):
  window = objc.IBOutlet()
  view = objc.IBOutlet()
  field = objc.IBOutlet()


  def awakeFromNib(self):
    self.window.makeFirstResponder_(self.field)
    self.field.selectText_(self)
    self.field.setDelegate_(self)
    self.controlTextDidChange_(None)

    def applicationDidFinishLaunching(self):
        # register cmd-control-J
        self.hotKeyRef = RegisterEventHotKey(38, cmdKey + controlKey, (0, 0),
                                             sendEvent_(), 0)

    def sendEvent_(self, theEvent):
        if theEvent.type() == NSSystemDefined and \
               theEvent.subtype() == kEventHotKeyPressedSubtype:
            self.activateIgnoringOtherApps_(True)
            NSRunAlertPanel(u'Hot Key Pressed', u'Hot Key Pressed',
                None, None, None)
        super(AppLauncher, self).sendEvent_(theEvent)

有什么想法我可以让这个工作(最好不涉及碳元素)?在

非常感谢。在


Tags: fromimportselfnone应用程序元素fielddef

热门问题