简体   繁体   中英

Get name of frontmost window in OS X with Accessibility API

I am trying to figure out how to get the name of the frontmost window using Cocoa/Objective-C. I am using the Accessibility API for other functions in my app, so it's fine if it's needed, but I'm not finding the command to do so. Does anyone know how I can find the name of the frontmost window in Objective-C? Thanks in advance.

You didn't say it exactly, but I'm guessing you want the frontmost window of your own application. I don't know if this is the greatest, but this works for me:

- (NSWindow*) frontmostWindowP {

NSArray*    windNumsArray   = [NSWindow windowNumbersWithOptions:0];
NSInteger   frontmostNumb   = [[windNumsArray objectAtIndex:1] integerValue];
NSArray*    windObjsArray   = [[NSApplication sharedApplication] windows];

for ( NSWindow* windP in windObjsArray )
    if ( [windP windowNumber] == frontmostNumb )
        return windP;

return 0;

}

"[NSWindow windowNumbersWithOptions:0]" returns an array of arbitrary looking integer "windowNumbers", like [ 10, 313, 319, 384 ]. The first number is always "10" for me, and it's junk. I guess maybe it represents the menu bar, or something. At any rate, the elements 1 thru N are the windowNumbers of your app's windows IN ORDER, from front to back. So that's why "[windNumsArray objectAtIndex:1]". The problem is that the "windowNumber" is otherwise pretty useless, but we're halfway there.

"[[NSApplication sharedApplication] windows]" returns an array of windows, this time NSWindow pointers, not in any trustable order. So all that remains is to find the NSWindow* with the right windowNumber, hence the for loop.

If you are interested in windows other than your own app's, look at the options for "NSWindow windowNumbersWithOptions".

You can use NSApplication's keyWindow and access the title property of NSWindow.For accessing other app's window you can refer this Getting the main window of an app via an NSRunningApplication instance

"Apple has traditionally been pretty locked-down about this sort of thing. NSRunningApplication itself was just introduced in 10.6, and as you said, it's a bit limited. Depending on what you want to do, the answer might be in the Accessibility framework or it might be the CGWindow API. You can use the processIdentifier from the NSRunningApplication to match it up with those APIs."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM