I have a child form opened from my main form as follows:
var cf = new ChildForm { Owner = this };
cf.Show();
The child form then does some drawing on another thread.
When a user tries to close the main form – if the child form is open – then a FormClosing event is fired first in ChildForm and then the same event is raised in the main form. On a FormClosing event the child form stops its drawing thread.
Users may try to close the main form when it contains unsaved data. Then they are shown a warning “Data not saved. Cancel close?“, by the main form’s FormClosing event handler. They can then cancel the save (i.e. the Cancel flag is set on the FormClosingEventArgs object by the main form’s FormClosing event handler).
However, by that point, the child form’s FormClosing event has already been raised, and it will have stopped its drawing thread. The child form does not know that it should now continue drawing (as if nothing had happened).
Is it possible to detect from the child form that the FormClosing event was cancelled by the main form? I would still like to stop the redrawing thread while the user is being asked to save data in the main form.
I would provide a solution based on interfaces. This way will be easy for you to have an uniform way of managing if the application can be closed or not. With the following implementation the parent-form is in charge of asking the child-window if is ready to be closed, the child does whatever actions has to be done and replies to main window.
Let suppose I have the interface
IManagedForm:Both forms (
Form1andChildForm) would implement it.Note that for this example I’m instantiating the
ChildFormin this way:Here comes first the implementation of the interface by
Form1:And finally your
ChildFormimplementation of the interface would look like this:Hope it is clear enough.