Export (0) Print
Expand All

ToolboxItem Class

Provides a base implementation of a toolbox item.

Namespace:  System.Drawing.Design
Assembly:  System.Drawing (in System.Drawing.dll)

[SerializableAttribute]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public class ToolboxItem : ISerializable

The ToolboxItem type exposes the following members.

  NameDescription
Public methodToolboxItem()Initializes a new instance of the ToolboxItem class.
Public methodToolboxItem(Type)Initializes a new instance of the ToolboxItem class that creates the specified type of component.
Top

  NameDescription
Public propertyAssemblyNameGets or sets the name of the assembly that contains the type or types that the toolbox item creates.
Public propertyBitmapGets or sets a bitmap to represent the toolbox item in the toolbox.
Public propertyCompanyGets or sets the company name for this ToolboxItem.
Public propertyComponentTypeGets the component type for this ToolboxItem.
Public propertyDependentAssembliesGets or sets the AssemblyName for the toolbox item.
Public propertyDescriptionGets or sets the description for this ToolboxItem.
Public propertyDisplayNameGets or sets the display name for the toolbox item.
Public propertyFilterGets or sets the filter that determines whether the toolbox item can be used on a destination component.
Public propertyIsTransientGets a value indicating whether the toolbox item is transient.
Public propertyLockedGets a value indicating whether the ToolboxItem is currently locked.
Public propertyPropertiesGets a dictionary of properties.
Public propertyTypeNameGets or sets the fully qualified name of the type of IComponent that the toolbox item creates when invoked.
Public propertyVersionGets the version for this ToolboxItem.
Top

  NameDescription
Protected methodCheckUnlockedThrows an exception if the toolbox item is currently locked.
Public methodCreateComponents()Creates the components that the toolbox item is configured to create.
Public methodCreateComponents(IDesignerHost)Creates the components that the toolbox item is configured to create, using the specified designer host.
Public methodCreateComponents(IDesignerHost, IDictionary)Creates the components that the toolbox item is configured to create, using the specified designer host and default values.
Protected methodCreateComponentsCore(IDesignerHost)Creates a component or an array of components when the toolbox item is invoked.
Protected methodCreateComponentsCore(IDesignerHost, IDictionary)Creates an array of components when the toolbox item is invoked.
Protected methodDeserializeLoads the state of the toolbox item from the specified serialization information object.
Public methodEqualsDetermines whether two ToolboxItem instances are equal. (Overrides Object.Equals(Object).)
Protected methodFilterPropertyValueFilters a property value before returning it.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeReturns the hash code for this instance. (Overrides Object.GetHashCode().)
Public methodGetType()Gets the Type of the current instance. (Inherited from Object.)
Public methodGetType(IDesignerHost)Enables access to the type associated with the toolbox item.
Protected methodGetType(IDesignerHost, AssemblyName, String, Boolean)Creates an instance of the specified type, optionally using a specified designer host and assembly name.
Public methodInitializeInitializes the current toolbox item with the specified type to create.
Public methodLockLocks the toolbox item and prevents changes to its properties.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnComponentsCreatedRaises the ComponentsCreated event.
Protected methodOnComponentsCreatingRaises the ComponentsCreating event.
Protected methodSerializeSaves the state of the toolbox item to the specified serialization information object.
Public methodToStringReturns a String that represents the current ToolboxItem. (Overrides Object.ToString().)
Protected methodValidatePropertyTypeValidates that an object is of a given type.
Protected methodValidatePropertyValueValidates a property before it is assigned to the property dictionary.
Top

  NameDescription
Public eventComponentsCreatedOccurs immediately after components are created.
Public eventComponentsCreatingOccurs when components are about to be created.
Top

  NameDescription
Explicit interface implemetationPrivate methodISerializable.GetObjectDataFor a description of this member, see the GetObjectData method.
Top

ToolboxItem is a base class for toolbox items that can be displayed in the toolbox of a design-time environment. A toolbox item typically represents a component to create when invoked on a design mode document. The ToolboxItem class provides the methods and properties needed to provide the toolbox with the display properties for the toolbox item, to create a component or components when used, and to serialize and deserialize itself for persistence within the toolbox database.

An instance of the ToolboxItem class can be configured with a name, bitmap, and type to create, without creating a class that derives from ToolboxItem. The ToolboxItem class also provides a base class for custom toolbox item implementations. A custom ToolboxItem can create multiple components. To implement a custom toolbox item, you must derive from ToolboxItem and override the CreateComponentsCore, Serialize, and Deserialize methods.

The following properties and methods must be configured for a ToolboxItem to function correctly:

  • The DisplayName property specifies the label for the toolbox item when displayed in a toolbox.

  • The TypeName property specifies the fully qualified name of the type of the component that the item creates. If a derived class creates multiple components, the TypeName property may or may not be used, contingent on whether a CreateComponentsCore method override depends on the value of this property.

  • The AssemblyName property specifies the assembly that contains the type of a component that the item creates.

  • The Bitmap property optionally specifies a bitmap image to display next to the display name for the toolbox item in the toolbox.

  • The Filter property optionally contains any ToolboxItemFilterAttribute objects that determine whether the toolbox item can be used on a particular component.

  • The CreateComponentsCore method returns the component instance or instances to insert where this tool is used.

  • The Serialize method saves the toolbox item to a specified SerializationInfo.

  • The Deserialize method configures the toolbox item from the state information contained in the specified SerializationInfo.

  • The Initialize method configures the toolbox item to create the specified type of component, if the CreateComponentsCore method has not been overridden to behave differently.

  • The Locked property indicates whether the properties of the toolbox item can be changed. A toolbox item is typically locked after it is added to a toolbox.

  • The Lock method locks a toolbox item.

  • The CheckUnlocked method throws an exception if the Locked property is true.

The following code example provides a component that uses the IToolboxService interface to add a text data format handler, or ToolboxItemCreatorCallback, to the toolbox. The data creator callback delegate passes any text data pasted to the toolbox and dragged onto a form to a custom ToolboxItem that creates a TextBox containing the text.

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Security.Permissions;
using System.Windows.Forms;

namespace TextDataTextBoxComponent
{
    // Component that adds a "Text" data format ToolboxItemCreatorCallback 
    // to the Toolbox. This component uses a custom ToolboxItem that  
    // creates a TextBox containing the text data.
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class TextDataTextBoxComponent : Component
    {
        private bool creatorAdded = false;
        private IToolboxService ts;

        public TextDataTextBoxComponent()
        {                     
        }

        // ISite override to register TextBox creator 
        public override System.ComponentModel.ISite Site
        {
            get
            {
                return base.Site;
            }
            set
            {
                if( value != null )
                {                    
                    base.Site = value;

                    if (!creatorAdded)
                    {
                        AddTextTextBoxCreator();
                    }
                }
                else
                {
                    if (creatorAdded)
                    {
                        RemoveTextTextBoxCreator();
                    }

                    base.Site = value;             
                }
            }
        }

        // Adds a "Text" data format creator to the toolbox that creates 
        // a textbox from a text fragment pasted to the toolbox. 
        private void AddTextTextBoxCreator()
        {
            ts = (IToolboxService)GetService(typeof(IToolboxService));

            if (ts != null) 
            {
                ToolboxItemCreatorCallback textCreator = 
                    new ToolboxItemCreatorCallback(this.CreateTextBoxForText);

                try
                {
                    ts.AddCreator(
                        textCreator, 
                        "Text", 
                        (IDesignerHost)GetService(typeof(IDesignerHost)));

                    creatorAdded = true;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(
                        ex.ToString(), 
                        "Exception Information");
                }                
            }
        }

        // Removes any "Text" data format creator from the toolbox.
        private void RemoveTextTextBoxCreator()
        {
            if (ts != null)             
            {
                ts.RemoveCreator(
                    "Text", 
                    (IDesignerHost)GetService(typeof(IDesignerHost)));            

                creatorAdded = false;
            }
        }

        // ToolboxItemCreatorCallback delegate format method to create  
        // the toolbox item. 
        private ToolboxItem CreateTextBoxForText(
            object serializedObject, 
            string format)
        {
            DataObject o = new DataObject((IDataObject)serializedObject);

            string[] formats = o.GetFormats();

            if (o.GetDataPresent("System.String", true))
            {
                string toolboxText = (string)(o.GetData("System.String", true));
                return (new TextToolboxItem(toolboxText));
            }

            return null;
        }

        protected override void Dispose(bool disposing)
        {
            if (creatorAdded)
            {
                RemoveTextTextBoxCreator();
            }
        }        
    }

    // Custom toolbox item creates a TextBox and sets its Text property 
    // to the constructor-specified text.
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 
    public class TextToolboxItem : ToolboxItem
    {
        private string text;
        private delegate void SetTextMethodHandler(Control c, string text);

        public TextToolboxItem(string text) : base()
        {
            this.text = text;
        }

        // ToolboxItem.CreateComponentsCore override to create the TextBox  
        // and link a method to set its Text property.
        [PermissionSet(SecurityAction.Demand, Name="FullTrust")] 
        protected override IComponent[] CreateComponentsCore(IDesignerHost host)
        {
            System.Windows.Forms.TextBox textbox = 
                (TextBox)host.CreateComponent(typeof(TextBox));

            // Because the designer resets the text of the textbox, use  
            // a SetTextMethodHandler to set the text to the value of  
            // the text data.
            Control c = host.RootComponent as Control;
            c.BeginInvoke(
                new SetTextMethodHandler(OnSetText), 
                new object[] {textbox, text});

            return new System.ComponentModel.IComponent[] { textbox };
        }        

        // Method to set the text property of a TextBox after it is initialized. 
        private void OnSetText(Control c, string text) 
        {
            c.Text = text;
        }
    }
}

The following code example demonstrates the use of the ToolboxItem class as a base class for a custom toolbox item implementation.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Data;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;

namespace CustomToolboxItem
{
    public class Form1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        private UserControl1 userControl11;
        private System.Windows.Forms.Label label1;

        public Form1()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.userControl11 = new CustomToolboxItem.UserControl1();
            this.SuspendLayout();
            //  
            // label1 
            //  
            this.label1.Location = new System.Drawing.Point(15, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(265, 62);
            this.label1.TabIndex = 0;
            this.label1.Text = "Build the project and drop UserControl1 from the toolbox onto the form.";
            //  
            // userControl11 
            //  
            this.userControl11.LabelText = "This is a custom user control.  The text you see here is provided by a custom too" +
                "lbox item when the user control is dropped on the form.";
            this.userControl11.Location = new System.Drawing.Point(74, 81);
            this.userControl11.Name = "userControl11";
            this.userControl11.Padding = new System.Windows.Forms.Padding(6);
            this.userControl11.Size = new System.Drawing.Size(150, 150);
            this.userControl11.TabIndex = 1;
            //  
            // Form1 
            //  
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.userControl11);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }

    // Configure this user control to have a custom toolbox item.
    [ToolboxItem(typeof(MyToolboxItem))]
    public class UserControl1 : UserControl
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Label label1;

        public UserControl1()
        {
            InitializeComponent();
        }

        public string LabelText
        {
            get
            {
                return label1.Text;
            }
            set
            {
                label1.Text = value;
            }
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //  
            // label1 
            //  
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(6, 6);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(138, 138);
            this.label1.TabIndex = 0;
            this.label1.Text = "This is a custom user control.  " + 
                "The text you see here is provided by a custom toolbox" +
                " item when the user control is dropped on the form.\r\n";
            this.label1.TextAlign = 
                System.Drawing.ContentAlignment.MiddleCenter;
            //  
            // UserControl1 
            //  
            this.Controls.Add(this.label1);
            this.Name = "UserControl1";
            this.Padding = new System.Windows.Forms.Padding(6);
            this.ResumeLayout(false);

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

    }

    // Toolbox items must be serializable.
    [Serializable]
    class MyToolboxItem : ToolboxItem
    {
        // The add components dialog in Visual Studio looks for a public 
        // constructor that takes a type. 
        public MyToolboxItem(Type toolType)
            : base(toolType)
        {
        }

        // And you must provide this special constructor for serialization. 
        // If you add additional data to MyToolboxItem that you 
        // want to serialize, you may override Deserialize and 
        // Serialize methods to add that data.  
        MyToolboxItem(SerializationInfo info, StreamingContext context)
        {
            Deserialize(info, context);
        }

        // Let's override the creation code and pop up a dialog. 
        protected override IComponent[] CreateComponentsCore(
            System.ComponentModel.Design.IDesignerHost host, 
            System.Collections.IDictionary defaultValues)
        {
            // Get the string we want to fill in the custom 
            // user control.  If the user cancels out of the dialog, 
            // return null or an empty array to signify that the  
            // tool creation was canceled. 
            using (ToolboxItemDialog d = new ToolboxItemDialog())
            {
                if (d.ShowDialog() == DialogResult.OK)
                {
                    string text = d.CreationText;

                    IComponent[] comps =
                        base.CreateComponentsCore(host, defaultValues);
                    // comps will have a single component: our data type.
                    ((UserControl1)comps[0]).LabelText = text;
                    return comps;
                }
                else
                {
                    return null;
                }
            }
        }
    }

    public class ToolboxItemDialog : Form
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;

        public ToolboxItemDialog()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //  
            // label1 
            //  
            this.label1.Location = new System.Drawing.Point(10, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(273, 43);
            this.label1.TabIndex = 0;
            this.label1.Text = "Enter the text you would like" + 
                " to have the user control populated with:";
            //  
            // textBox1 
            //  
            this.textBox1.AutoSize = false;
            this.textBox1.Location = new System.Drawing.Point(10, 58);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(270, 67);
            this.textBox1.TabIndex = 1;
            this.textBox1.Text = "This is a custom user control.  " + 
                "The text you see here is provided by a custom toolbox" +
                " item when the user control is dropped on the form.";
            //  
            // button1 
            //  
            this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.button1.Location = new System.Drawing.Point(124, 131);
            this.button1.Name = "button1";
            this.button1.TabIndex = 2;
            this.button1.Text = "OK";
            //  
            // button2 
            //  
            this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.button2.Location = new System.Drawing.Point(205, 131);
            this.button2.Name = "button2";
            this.button2.TabIndex = 3;
            this.button2.Text = "Cancel";
            //  
            // ToolboxItemDialog 
            //  
            this.AcceptButton = this.button1;
            this.CancelButton = this.button2;
            this.ClientSize = new System.Drawing.Size(292, 162);
            this.ControlBox = false;
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = 
                System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "ToolboxItemDialog";
            this.Text = "ToolboxItemDialog";
            this.ResumeLayout(false);

        }

        public string CreationText
        {
            get
            {
                return textBox1.Text;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft