Skip to content

Instantly share code, notes, and snippets.

@ljos
Last active January 25, 2024 04:16
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ljos/3040846 to your computer and use it in GitHub Desktop.
Save ljos/3040846 to your computer and use it in GitHub Desktop.
Find the frontmost/active window in OS X
# Copyright @ Bjarte Johansen 2012
# License: http://ljos.mit-license.org/
from AppKit import NSApplication, NSApp, NSWorkspace
from Foundation import NSObject, NSLog
from PyObjCTools import AppHelper
from Quartz import kCGWindowListOptionOnScreenOnly, kCGNullWindowID, CGWindowListCopyWindowInfo
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, notification):
workspace = NSWorkspace.sharedWorkspace()
activeApps = workspace.runningApplications()
for app in activeApps:
if app.isActive():
options = kCGWindowListOptionOnScreenOnly
windowList = CGWindowListCopyWindowInfo(options,
kCGNullWindowID)
for window in windowList:
if window['kCGWindowOwnerName'] == app.localizedName():
NSLog('%@', window)
break
break
AppHelper.stopEventLoop()
def main():
NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
@stefanocoding
Copy link

Thank you for share this piece of code. I was struggling to do the same on Swift and your Python implementation saved me. 😃

@gebv
Copy link

gebv commented Oct 20, 2015

How to identify the active window (kCGWindowNumber)?
For example from Chrome can be several windows but the top one

@percontation
Copy link

I needed to modify the kCGWindowOwnerName/localizedName check to be window['kCGWindowOwnerPID'] == app.processIdentifier(). Specifically, for iTerm the kCGWindowOwnerName is "iTerm" but the app.localizedName() is "iTerm2".

@linrock
Copy link

linrock commented Jan 18, 2020

Make sure pyobjc is installed before trying to run this code - ex. pip install pyobjc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment