getting selected text from any app Panther

Hello - long time reader, first time writer – thanks in advance for any assistance.

So, this is a followup to a previous thread. The original question was “How do I get the selected text from the active application, whatever app it is”. The code solution, which used GUI scripting, looked like this:

tell application "System Events"
	set theProcess to every process whose frontmost is true
	
	tell process theProcess
		key down {command}
		keystroke "c"
		key up {command}
	end tell
	return the clipboard contents
end tell

I just discovered this code the day of Panther’s release, and so Jaguar’s GUI scripting extension was no longer available. I’ve since upgraded to Panther, and tried this out, but… the clipboard contents don’t update until I’ve run this twice! That is, the first run, nothing happens, the second run, the results of the first run are reported, the third time, the second run, etc.

It would appear that the clipboard contents don’t update as quickly as the script is executing. But I could have it wrong.

So two questions:
a) can anyone make the above code work?
b) does anyone have a better suggestion for generically collecting text into an Applescript variable from any selection in any app? I’d really prefer to avoid the whole GUI scripting thing if possible, as it just feels a little messy to me…

Thanks a lot -
jb

I had a similar problem with sending keystrokes for cut and paste using System Events.

I foun that the following worked more reliably (no idea why):


tell application "System Events"
	tell process "ical"
		set frontmost to true
		tell menu "Edit" of menu bar item "Edit" of menu bar 1
			click menu item "Cut"
			click menu item "Paste"
		end tell
	end tell
end tell

I was addressing this to ical, but I presume the syntax would be the same for other apps.