It is a common requirement when using User Controls to detect that the Parent Form or main form is closing.
Presently, I am working on a distributed smart client application that is full of user controls. Most, if not all of these user controls will be getting data by calling a Windows Communication Foundation service (A good tutorial on WCF is available in an earlier blog post here).
When you instantiate a Service Reference client object, it is imperative that you call client.Close() to free up any resources when the control is closed. As there is no FormClosing event in a winforms UserControl, you will need to override the ParentForm.FormClosing event. In this example I have a windows form with a user control on it. When you close the form the event in the user control is raised.
Note: Visual basic example is below
public partial class UserControl1 : UserControl
protected override void OnCreateControl()
this.ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
if (MessageBox.Show("Would you like to close the parent form?", "Close parent form?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
e.Cancel = true;
Public Class UserControl1
Protected Overloads Overrides Sub OnCreateControl()
AddHandler Me.ParentForm.FormClosing, AddressOf ParentForm_FormClosing
Private Sub ParentForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
If MessageBox.Show("Would you like to close the parent form?", "Close parent form?", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
e.Cancel = True
You can then call the client.Close() (or whatever action you desire) instead of MessageBox.Show() in ParentForm_FormClosing event