Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mathcolo

macrumors 6502a
Original poster
Sep 14, 2008
860
16
Boston
Hi.. I'm making a menu bar application and I'm trying to get the currently selected text.

This is my code so far:

Code:
	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

Moderator emeritus
Jun 15, 2000
7,958
7
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

macrumors 6502a
Original poster
Sep 14, 2008
860
16
Boston
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

Moderator emeritus
Jun 15, 2000
7,958
7
Depends. Might be easier with AppleScript, but I've never used the accessibility APIs so that would also take research.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.