Skip to content

Instantly share code, notes, and snippets.

@gerad
Created January 20, 2012 04:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gerad/1645235 to your computer and use it in GitHub Desktop.
Save gerad/1645235 to your computer and use it in GitHub Desktop.
get the name and path of the frontmost window using the carbon mac os accessibility api
// http://stackoverflow.com/questions/2107657/mac-cocoa-getting-a-list-of-windows-using-accessibility-api
// http://stackoverflow.com/questions/853833/how-can-my-app-detect-a-change-to-another-apps-window
// http://cocoatutorial.grapewave.com/tag/axuielementcopyattributevalue/
- (NSDictionary *)axInfoForProcessIdentifier:(NSNumber *)processIdentifier
{
NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:2];
pid_t pid = (pid_t) [processIdentifier integerValue];
AXUIElementRef app = AXUIElementCreateApplication(pid);
AXUIElementRef frontWindow = nil;
NSString *title = nil;
NSString *path = nil;
AXError err;
// get the focused window for the application
err = AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute,
(CFTypeRef *) &frontWindow);
if (err == kAXErrorSuccess) {
// get the title for the window
err = AXUIElementCopyAttributeValue(frontWindow, kAXTitleAttribute, (CFTypeRef *) &title);
if (err == kAXErrorSuccess) {
[ret setObject:title forKey:@"title"];
[title autorelease];
}
// get the document path for the window
err = AXUIElementCopyAttributeValue(frontWindow, kAXDocumentAttribute, (CFTypeRef *) &path);
if (err == kAXErrorSuccess) {
[ret setObject:path forKey:@"path"];
[path autorelease];
}
CFRelease(frontWindow);
}
CFRelease(app);
return ret;
}
@cshroba-figma
Copy link

Here's how to do it from the command line!

To get the active application:

➜ osascript -e 'tell application "System Events" to tell (first process whose frontmost is true) to return name'

To get the active window's title:

➜ osascript -e 'tell application "System Events" to tell (first process whose frontmost is true) to return name of window 1'

And to get both (to avoid a race condition where the user changes windows between the two calls):

➜ osascript -e 'tell application "System Events" to tell (first process whose frontmost is true) to return {name, name of window 1}'

Source: https://forum.keyboardmaestro.com/t/how-do-i-get-the-name-of-the-frontmost-window/2711/2

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