July 29, 2009

How to Get a Parent Form from a Component

I found much of this at Code Project, but I think my implementation is cleaner.

Since a component doesn’t have a Parent property like a control does it is often difficult to Invoke in a component which is a pity since a component is more likely to need it. This solution creates an abstract class that adds the Parent property to the component class. If you merely derive your class from the AdvancedComponent class instead of from the Component class you will get the Parent property as well as the FindForm() method.

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace MyComponents
{
public class AdvancedComponent : Component
{
private Form m_parent_form;
public AdvancedComponent()
: base() { }
/// <summary>
/// Overrides the ISite property
/// so that it is set when the
/// component is placed on a form.
/// </summary>
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
GetFormInstance();
}
}
private void GetFormInstance()
{
IDesignerHost host = null;
if (base.Site != null)
{
host = base.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
m_parent_form = host.RootComponent as Form;
}
}
}
/// <summary>
/// Creates a Parent property
/// that can be used to find the
/// parent form.
/// </summary>
public Form Parent
{
get { return m_parent_form; }
set
{
m_parent_form = value;
}
}
/// <summary>
/// Implements a FindForm method
/// similar to Control.FindForm
/// </summary>
/// <returns>The contents of the Parent property</returns>
public Form FindForm()
{
return Parent;
}
}
}

No comments:

Post a Comment