Something strange with script

Hello!
I’ve wrote a script to make a picture of the screen selection, open Preview and press some keystrokes to make an annotation. The problem – script does work but not always. I’ve tried to lunch it from Applescript editor, from FileMaker… Unpredictably works 2 times of 10. :frowning: Could somebody figure out my mistake?
Thanks.

The script:

do shell script “screencapture -i -c -tjpeg $FILE”
tell application “Preview”
activate
end tell
tell application “System Events”
tell process “Preview”
set frontmost to true
keystroke “n” using command down
keystroke “a” using {command down, shift down}
end tell
end tell

Model: MacPro 4,1
AppleScript: 2.1.2
Browser: Safari 533.19.4
Operating System: Mac OS X (10.6)

Seems to work ok here. Try adding a delay between the two keystrokes.

do shell script "screencapture -i -c -tjpeg $FILE"
tell application "Preview"
	activate
end tell
tell application "System Events"
	tell process "Preview"
		set frontmost to true
		keystroke "n" using command down
		delay 0.2
		keystroke "a" using {command down, shift down}
	end tell
end tell

Best wishes

John M

Thanks, John M

The same stuff with delay. Script stops before pressing keys in Preview menu. Error beep as menu item can’t be pressed. Worked OK yesterday.

GUI Scripting’s often problematic. Is this any more successful?

do shell script "screencapture -i -c -tjpeg"
tell application "Preview"
	activate
end tell
tell application "System Events"
	tell application process "Preview"
		set frontmost to true
		set wc to (count windows)
		-- Identify the "New from Clipboard" menu item. Filter only works in SL.
		set nfc to first menu item of menu 1 of menu bar item 3 of menu bar 1 whose value of attribute "AXMenuItemCmdChar" is "N" and value of attribute "AXMenuItemCmdModifiers" is 0
		-- Or, with a looser filter which works in both Tiger and SL:
		-- set nfc to first menu item of menu 1 of menu bar item 3 of menu bar 1 whose value of attributes contains "N" and value of attributes contains 0

		-- Wait until the menu item's enabled.
		repeat until (nfc's enabled)
			delay 0.2
		end repeat
		-- Action the menu item.
		perform nfc's action "AXPress"
		-- Wait until the number of Preview windows increases.
		repeat until ((count windows) > wc)
			delay 0.2
		end repeat
		-- Show the Annotations Toolbar.
		keystroke "a" using {command down, shift down}
	end tell
end tell

Thank you! It works by now.