You could try using a Java Robot to send a Key Press and Key Release event. However, this is not recommended.
You should be creating your loop to sometimes check a flag indicating whether it is being asked to stop. The cancel button should set the flag.
I do not know enough about app designer to talk about how to create shared values for it.