How to use Mac OS X NSEvents within wxPython appli

2019-09-18 02:54发布

问题:

I am writing an application that has to react to system wide keypresses on Mac OS X.

So I found some key logger examples that should work and hit a wall, because all examples are based on NSSharedApplication() and PyObjC AppHelper.runEventLoop() while my application is written in wxPython.

Here I post a modification of the simplest example from https://github.com/ljos that I thought it should work. But it does not.

from AppKit import *
import wx

class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, aNotification):
        NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)

def handler(event):
    print (u"%@", event)

app = wx.App()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
app.MainLoop()

It is obvious that the MainLoop() doesn't catch the delegated NSEvents.

After app = wx.App() the NSApp() is returned correctly. So why doesn't this work? How do I make it work?

回答1:

As nobody answered I went searching around with different angle in view.

So I discovered that Quartz module can be used to get to keyboard and mouse events. No custom loop needed, therefore wx.App() and wx.App.MainLoop() aren't getting in the way.

I also found a nice package named pynput that does just that for me, thus sparing me plenty of time. Quartz is pretty complicated, a lot of scrambled names for functions and constants. But it does a good job.