Search code examples
c#.netwinformsuser-controlswindows-forms-designer

Determine design-time context of a custom winforms control


Suppose I have a custom WinForms control:

public class MyBaseControl : Control
{
     ...
}

which is extended like:

public class MyControl : MyBaseControl
{
     ...
}

By checking the this.DesignMode property flag it is fairly trivial to determine whether or not the control is being visually designed, however is there a way to determine if the MyControl itself is being designed, versus being manipulated on a from at design time?


To provide additional clarification, within the MyControl class, I am trying to differentiate between design-time when the component itself is being designed:

"Control" designer

and when the component is added to a form from the toolbox at design-time:

enter image description here


Solution

  • You can check if the control is root in designer or not.
    You can get the IDesignerHost service and then check the RootComponent property to see if your control is the root component for current designer or not.

    using System.Windows.Forms;
    using System.ComponentModel.Design;
    public partial class MyBaseControl : UserControl
    {
        public MyBaseControl()
        {
            InitializeComponent();
        }
    
        public bool IsRootDesigner
        {
            get
            {
                var host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
                if (host != null)
                    return host.RootComponent == this;
    
                return false;
            }
        }
    }