I have a program where the user may hit Stop and stop the program while running at any given time.

I'm looking for a way to detect if the user hits the Stop button in Script Editor (producing the -128 "User canceled" error), so I can do a little cleanup before the program closes.

Is there a way to do this?


You can use a try block like this:

repeat -- your loop
        -- your code in the loop
    on error err number n
        if n = -128 then -- User canceled
            -- code to  cleanup before the program closes
            return -- exit this script
        end if
    end try
end repeat
| improve this answer | |

Script Editor is above the script. If one hits stop there, no further line is executed.

If, on the other side, you created an application from it, hitting any button displayed there (e.g. through display dialog), will trigger whatever you programmed that button to do.

| improve this answer | |
  • In my program, a loop is running constantly and I want to be able to break out of it at any time. Is there a way to have a dialog with button that can do that? – user3932000 Sep 6 '16 at 1:21
  • If you use your loop (or a loop, which does not wait too long), you can ask for a state of a variable to exit the repeat loop. Define that variable globally and change it inside an AppleScript handler called on quit. When you hit Application Menu > Quit (or the keyboard equivalent) your program will run through it, change the variable and break out of that loop. I was not able to quickly find it, but Apple has a PDF titled "AppleScript Language Guide", which also describes the on quit handler and should give you further ideas. – Phoenix Sep 7 '16 at 7:02
  • If you expand your question with your comment, I will also do it with my answer. – Phoenix Sep 7 '16 at 7:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .