简体   繁体   中英

How to use Mac OS X NSEvents within wxPython application?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM