Prevent Adding Component More than once

Question: I'm developing a C# component, I want to prevent the user from adding this component to the Form if the Form already has an instance of the component.

Answer: You can create a custom ComponentDesigner for your component, override its InitializeNewComponent() method to judge wether there's already an instance existes, if so, just return from this method. I write the following sample for your information:
[Designer(typeof(myComponentDesigner))]
class myComponent : Component
{
    public myComponent(IContainer container)
    {
        // Add object to container's list so that
        // we get notified when the container goes away
        container.Add(this);
    }
}

class myComponentDesigner : ComponentDesigner
{
    public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
    {
        IDesignerHost service = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
        if (service == null) return;
        ComponentCollection cc = service.Container.Components;

        int count = 0;
        foreach (Component c in cc)
        {
            if (c.GetType() == this.Component.GetType() )
            {
                count++;
                if (count > 1)
                {
                    service.Container.Remove(this.Component);
                    MessageBox.Show(
                       "You cannot add more than one instance of the myComponet!");
                    return;
                }
            }
        }

        base.InitializeNewComponent(defaultValues);
    }
}
 
原文地址:https://www.cnblogs.com/eastson/p/4273953.html