Finding when ActiveApplication changes on OSX via Python

Is there a way to find when activeApplication changes on OSX via Python and AppKit? I know how to find launchApplication and activeApplication (see my other question here: Finding the currently active window on Mac OS X using Python )

0


source to share


2 answers


I have an OS X app that is doing this poll using NSTimer . I tried looking for distributed notifications to see if I could find a better way to do this, but I couldn't see anything terribly useful.

I got notifications when the app was started or quit . which is at least a little helpful. You can see their registration when my controller wakes up .



This application was very helpful for me and even polling once a second hardly uses the processor. If I could make it a more event driven, I would, however. :)

+1


source


I don't know of an "official" / good way to do this, but one hacky way to do it is to listen to any common notifications and see which ones always fire when the closest app changes, so you can listen to this:

You can install something like this:

def awakeFromNib(self):
    NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(
        self, 'someNotification:', None, None)

def someNotification_(self, notification):
    NSLog(notification.name())

      

After you find a notification that is always triggered when switching applications, you can replace the first "No" in the addObserver_etc_ call with the name of this notification and check the nearest application in the "someNotification_" method.



In my case, I noticed that "AppleSelectedInputSourcesChangedNotification" is fired every time I switch applications, so I would listen to that.

Keep in mind that this can break at any time, and you will check for changes in the front-most application more often than necessary.

There must be a better way though .. hopefully :)

0


source







All Articles