We can listen to the Form’s FormClosing event and in the event handler function, we can run the codes to do what we want. For detailed information, please refer to this MSDN documentation:
FormClosing event occurs before a form is being closed. To cancel the closure of a form, in that form’s FormClosing event handle, we should set the FormClosingEventArgs’s Cancel property to true.