<p>我最近编写了一个<a href="https://github.com/mjpieters/quodlibet_plugins/blob/master/events/osxmmkey.py" rel="nofollow noreferrer">extension</a>到<a href="https://code.google.com/p/quodlibet/" rel="nofollow noreferrer">quodlibet</a>捕获多媒体密钥的代码(因为它被吸收到了qodlibet中);对于您的设置,同样的过程也适用。在</p>
<p>我使用Quartz<a href="https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html" rel="nofollow noreferrer">^{<cd1>} hook</a>和事件循环,以及Cocoa AppKit框架来破译密钥代码来实现这一点。在</p>
<p>以下代码注册一个python回调,该回调被传递给全局键按下,并启动事件循环:</p>
<pre><code>import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent
# Set up a tap, with type of tap, location, options and event mask
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap, # Session level is enough for our needs
Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter
Quartz.kCGEventTapOptionListenOnly, # Listening is enough
Quartz.CGEventMaskBit(NSSystemDefined), # NSSystemDefined for media keys
keyboardTapCallback,
None
)
runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
Quartz.CFRunLoopGetCurrent(),
runLoopSource,
Quartz.kCFRunLoopDefaultMode
)
# Enable the tap
Quartz.CGEventTapEnable(tap, True)
# and run! This won't return until we exit or are terminated.
Quartz.CFRunLoopRun()
</code></pre>
<p>我只为系统定义的键(媒体键)定义了一个tap;您必须指定一个不同的事件掩码(<code>CGEventMaskBit</code>和一个或多个<a href="https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/doc/uid/TP40003550-CH3g-C016985" rel="nofollow noreferrer">Event Types</a>);例如,<code>Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp)</code>用于键启动事件。在</p>
<p>回调应该有以下签名(它实现了<a href="https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/doc/uid/TP40003550-CH1g-BBCHIIJJ" rel="nofollow noreferrer">^{<cd4>} method from the Quartz API</a>:</p>
^{pr2}$
<p>我将Quartz事件转换为<a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/Reference/Reference.html" rel="nofollow noreferrer">^{<cd5>}</a>,因为我在Mac多媒体密钥上能找到的所有信息都与该类有关。在</p>
<p>原则上,你也可以用appkitapi实现同样的功能,但是你的Python应用程序被视为一个Mac应用程序(在Dock中可以看到一个图标和所有东西),而我希望它完全保持在后台。在</p>