Created
January 20, 2012 04:45
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's how to do it from the command line!
To get the active application:
To get the active window's title:
And to get both (to avoid a race condition where the user changes windows between the two calls):
Source: https://forum.keyboardmaestro.com/t/how-do-i-get-the-name-of-the-frontmost-window/2711/2