Detect Stop program

Hello All

Here is our scenario. We have a UR5 and we have an application where it is connected to a 2 Cameras. 1st camera we use to setup the Pick Up point. 2nd camera is used to validate if product is Ok or not. The UR5 and cameras are connected using Sockets. We have a c# application that interacts as Socket Server. what we looking to do is that if the program in the robot is stop, it does not close automatically the open sockets so I want to know if there is a way that once the stop Button is set in the Robot it can send to a subroutine where all sockets could be closed and in that way next chance the main program starts it can reestablish connection with the main server.

I’m looking to find something similar like for example in windows form when you closing a Form you can perform actions. So when the stop button is pressed on the runing program how can I perform some tasks (Like Close all Sockets).

Really appreciate all your comments and suggestions.

Best Regards
Rodolfo