It's hard to remember Objective-C, so I've just scratched it, but I wrote it using Python (and PyObjC):
active_app_logger.py
from AppKit import *
from PyObjCTools import AppHelper
def main():
nc = NSWorkspace.sharedWorkspace().notificationCenter()
nc.addObserver_selector_name_object_(
Observer.new(),
"handle:",
NSWorkspaceDidActivateApplicationNotification,
None
)
AppHelper.runConsoleEventLoop(installInterrupt=True)
class Observer(NSObject):
def handle_(self, noti):
"""Process called when the active application is switched"""
info = noti.userInfo().objectForKey_(NSWorkspaceApplicationKey)
for n in ["bundleIdentifier", "localizedName", "bundleURL",
"executableURL", "launchDate"]:
v = info.valueForKey_(n)
print("%s (%s):\t%s" % (n, v.className(), v))
print("--")
main()
Run it on your device and switch applications in the order of Google Chrome → iTerm:
$ python cocoa_active_window.py
bundleIdentifier (__NSCFString): com.google.Chrome
localizedName (__NSCFString): Google Chrome
bundleURL (NSURL): file:///Applications/Google%20Chrome.app
executableURL (NSURL): file:///Applications/Google%20Chrome.app/Contents/MacOS/Google%20Chrome
launchDate (__NSDate): 2015-01-02 05:09:26 +0000
--
bundleIdentifier (__NSCFString): com.googlecode.iterm2
localizedName (NSTaggedPointerString): iTerm
bundleURL (NSURL): file:///Applications/iTerm.app
executableURL (NSURL): file:///Applications/iTerm.app/Contents/MacOS/iTerm
launchDate (__NSTaggedDate): 2015-01-02 05:59:29 +0000
--
PyObjC must be installed to run this script:
$ sudo pip install pyobjc
The operating environment of the script is:
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.10.1
BuildVersion: 14B25
$ xcodebuild -version
Xcode 6.1.1
Build version 6A2008a
$ python --version
Python 2.7.6
$ pip show 'pyobjc' | grep Version
Version: 3.0.4
I chose PyObjC because it seemed to have more materials than Ruby (RubyCocoa), which I'm used to a little, but if neither Python nor PyObjC can be used easily in Objective-C and I have never created a Mac OS X application, I will obediently start from Objective-C. It might have been easier to remember. It was hard.
It seems that you need to touch NSAccessibility
to get information on the active window, so give up. Is NSAccessibility
an API with a solid policy that allows access to critical information? Also, I couldn't find it in PyObjC, but isn't it bound?
Recommended Posts