2

I'm referencing this old thread: system wide shortcut for Mac OS X

I have been attempting to use this to create a global hotkey for osx since my old method of using pyglobalshortcuts no longer works with PyQt5. The trouble is that when I listen for 'kCGEventKeyUp' or 'kCGEventKeyDown' in the 'CGEventTapCreate' function, the program exits with code '-11'. Here's the code I was trying:

import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent

def keyboardTapCallback(proxy, type_, event, refcon):
    keyEvent = NSEvent.eventWithCGEvent_(event)
    if keyEvent is None:
        pass
    else:
        print keyEvent


tap = Quartz.CGEventTapCreate(
                              Quartz.kCGSessionEventTap,
                              Quartz.kCGHeadInsertEventTap,
                              Quartz.kCGEventTapOptionListenOnly,
                              # Quartz.kCGEventMaskForAllEvents, 
                              Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp),
                              keyboardTapCallback,
                              None
                             )


runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
                          Quartz.CFRunLoopGetCurrent(),
                          runLoopSource,
                          Quartz.kCFRunLoopDefaultMode
                         )

Quartz.CGEventTapEnable(tap, True)

try:
    Quartz.CFRunLoopRun()
except Exception as e:
    print e, "<<<<<<<<<<<<<<<"

I also tried replacing 'Quartz.kCGEventMaskBit(Quartz.kCGEventKeyUp)' with 'Quartz.kCGEventMaskForAllEvents' and while this did not fail it also isn't returning any alphanumeric keys (I need to be able to use 'ctrl+shift+d' as my shortcut).

Am I terribly far off with being able to detect this shortcut in Quartz or is there a better method in OSX?

Thanks, -Mark

Community
  • 1
  • 1
huitlacoche
  • 173
  • 1
  • 2
  • 15
  • This code runs fine without any exit code but doesn't print anything..i modified it to listen to mouse move, mouse down etc events too to see if its working but can't get it print anything..no error, nothing..i am using python 2.7 to run – Kaushik Wavhal Oct 09 '21 at 14:55

1 Answers1

1

I think I just figured it out. I'm using a shared keyboard through Synergy. When I went back to my mac keyboard, it could detect the key events.

Thanks! -Mark

huitlacoche
  • 173
  • 1
  • 2
  • 15