Skip to content

Instantly share code, notes, and snippets.

@sixpetrov
Forked from gerad/axInfoForProcessIdentifier.m
Created November 20, 2017 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sixpetrov/d380fff5a3c3c9cc0624a6d1250fdeb2 to your computer and use it in GitHub Desktop.
Save sixpetrov/d380fff5a3c3c9cc0624a6d1250fdeb2 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment