How to intercept events from specific windows in OSX

536 Views Asked by At

I want to have the following workflow:

  • User presses hotkey, or status bar menu button
  • User clicks on a window
  • Window is now "registered" in my app
  • App intercepts mouse events from all registered windows

I've read a lot on CGEvents, CGEventTaps and NSEvents. I can intercept global events and post new ones using CGEvents and CGEventTaps but there is not window information like windowNumber in NSEvent, only PSD (and I'm not sure how to use those), so I can't filter out events from non-registered windows. NSEvent, on the other hand, doesn't let me to intercept global events, only local ones through a localMonitor.

How could I achieve the desired functionality?

1

There are 1 best solutions below

0
On

You can use the Mac OS X Accessibility API to get details about the currently focused window or application.

The UIElementInspector Apple Sample Code gives many examples.

// Given a uiElement and its attribute, return the value of an accessibility object's attribute.
+ (id)valueOfAttribute:(NSString *)attribute ofUIElement:(AXUIElementRef)element;

Use the kAXFocusedApplicationAttribute or kAXFocusedWindowAttribute attributes with valueOfAttribute:ofUIElement: to get the window/app when you "register" it with your app.

When a CGEvent comes in, compare the currently focused window/app to your list of registered windows/apps to determine if the event should be intercepted.