NSEvent global event monitoring in background
Asked Answered
E

1

23

I am writing a simple Mac application designed to run in the background and perform certain actions whenever the user clicks the mouse button. The app is written in Python using PyObjC. I am using addGlobalMonitorForEventsMatchingMask to watch for NSLeftMouseDown events:

NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSLeftMouseDownMask, handler)

This code works perfectly when running in the terminal. However, when I bundle it as a standalone app (using py2app) and then launch it, the app doesn't receive any events at first. (Or at least, if it does, it doesn't run the code in my handler method.) Only when I click on the app in the Dock does it start receiving events, and after that, it continues to receive events even after it returns to the background. But it doesn't receive anything until activated once.

My question is: How can I get my app to start receiving events as soon as it is launched, without having to be activated first by clicking the Dock icon? Is this some known quirk of NSEvents, or is there perhaps something wrong with my run loop in PyObjC?

Any help or guidance is greatly appreciated!

Edit: Upon further testing, it seems that, in fact, my app spontaneously starts receiving notifications about ten seconds after launch, regardless of whether I activate it. Which is slightly annoying, but fine.

However, if I run the app with either LSUIElement = true or LSBackgroundOnly = true in my Info.plist (which I ultimately want to do, since this app should only run in the background and never appear in the Dock), I never receive notifications. So I am still stuck.

Emancipate answered 24/7, 2013 at 22:27 Comment(6)
Are you sure, that this line executes when app starts?Huntlee
Can you post a minimal, complete, valid example that others can use to reproduce and maybe debug the problem?Ophthalmitis
check if it meets the AppStore's guidelines. but if it's for personal use, try it with Xcode. want an example?Cordilleras
"Note that your handler will not be called for events that are sent to your own application." - just to check, isn't this your case? I.e. you trying to check mouse events while your application is active?Hyaluronidase
What is your OSX version?Enlistee
where do you call NSEvent.addGlobalMonitorForEventsMatchingMask_handlerPerloff
O
1

As you said "Only when I click on the app in the Dock does it start receiving events" , that means the handler gets registered after you click on the app in the Dock.

So it depends on at which point in the code you are calling this : NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSLeftMouseDownMask, handler) , that is registering the handler.

You should register the handler in appdidfinishlaunching function.

Orthopsychiatry answered 9/4, 2014 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.