HotKeyPython

Demonstrates how to use Carbon global hot keys from a PyObjC application. Also demonstrates how to use a NSApplication subclass.

Note

Requires Python 2.x because the code uses the Carbon package that was removed in Python 3.0.

Not only that, you need to run the example in 32-bit mode as well because some of the Carbon function’s aren’t available in 64-bit mode.

Sources

HotKey.py

"""HotKey.py

An example that shows how to use Carbon HotKeys from a PyObjC application,
and how to use an NSApplication subclass.

To build the demo program, run this line in Terminal.app:

    $ python setup.py py2app -A

This creates a directory "dist" containing HotKey.app. (The
-A option causes the files to be symlinked to the .app bundle instead
of copied. This means you don't have to rebuild the app if you edit the
sources or nibs.)

NOTE: This example requires Python 2 because it uses the "Carbon"
      module that was removed in Python 3.
"""
from Carbon.CarbonEvt import GetApplicationEventTarget, RegisterEventHotKey
from Carbon.Events import cmdKey, controlKey

import Cocoa
from objc import super
from PyObjCTools import AppHelper

kEventHotKeyPressedSubtype = 6
kEventHotKeyReleasedSubtype = 9


class HotKeyApp(Cocoa.NSApplication):
    def finishLaunching(self):
        super(HotKeyApp, self).finishLaunching()
        # register cmd-control-J
        self.hotKeyRef = RegisterEventHotKey(
            38, cmdKey | controlKey, (0, 0), GetApplicationEventTarget(), 0
        )

    def sendEvent_(self, theEvent):
        if (
            theEvent.type() == Cocoa.NSSystemDefined
            and theEvent.subtype() == kEventHotKeyPressedSubtype
        ):
            self.activateIgnoringOtherApps_(True)
            Cocoa.NSRunAlertPanel(
                "Hot Key Pressed", "Hot Key Pressed", None, None, None
            )
        super(HotKeyApp, self).sendEvent_(theEvent)


if __name__ == "__main__":
    AppHelper.runEventLoop()

setup.py

"""
Script for building the example.

Usage:
    python2 setup.py py2app
"""
from setuptools import setup

plist = {"NSPrincipalClass": "HotKeyApp"}


setup(
    app=["HotKey.py"],
    data_files=["English.lproj"],
    options={"py2app": {"plist": plist}},
    setup_requires=["py2app", "pyobjc-framework-Cocoa"],
)