PDA

View Full Version : Getting array of all system windows




mathcolo
Mar 14, 2009, 10:27 AM
Hi.. I'm making a menu bar application and I'm trying to get the currently selected text.

This is my code so far:

NSString *string;

NSWindow *frontWindow = [[NSApp orderedWindows] objectAtIndex:0];

id firstResponder = [frontWindow firstResponder];


if ([firstResponder isKindOfClass:[NSText class]])
{
if ([firstResponder selectedRange].length == 0)
{
return;
}
else
{
string = [[firstResponder string] substringWithRange:[firstResponder selectedRange]];
}

}

The problem with this is that the menu bar app has no windows open, and therefore says there is no object at index 0 when that code is run. Instead of getting the orderedWindows array from NSApp (which is the menu bar app itself), where can I get the array for the windows open on the entire system?



kainjow
Mar 14, 2009, 10:57 AM
You can't get the selected text of another app through Cocoa directly. There is an API for getting all system windows (spotlight CGWindow.h) but NSWindows are only valid for your application. You would need to use the accessibility APIs or AppleScript's UI scripting instead.

mathcolo
Mar 14, 2009, 11:04 AM
You can't get the selected text of another app through Cocoa directly. There is an API for getting all system windows (spotlight CGWindow.h) but NSWindows are only valid for your application. You would need to use the accessibility APIs or AppleScript's UI scripting instead.

Which method would you use? There seem to be ups and downs for both methods. I'd prefer not to venture in the AppleScript studio world or bother with Accessibility stuff, but if I must....

kainjow
Mar 14, 2009, 12:57 PM
Depends. Might be easier with AppleScript, but I've never used the accessibility APIs so that would also take research.