ToolboxItem ToolboxItem ToolboxItem ToolboxItem Class

定義

提供工具箱項目的基底實作。Provides a base implementation of a toolbox item.

public ref class ToolboxItem : System::Runtime::Serialization::ISerializable
[System.Serializable]
public class ToolboxItem : System.Runtime.Serialization.ISerializable
type ToolboxItem = class
    interface ISerializable
Public Class ToolboxItem
Implements ISerializable
繼承
ToolboxItemToolboxItemToolboxItemToolboxItem
衍生
屬性
實作

範例

下列程式碼範例提供的元件會使用IToolboxService介面, 將文字資料格式處理常式或ToolboxItemCreatorCallback加入至 [工具箱]。The following code example provides a component that uses the IToolboxService interface to add a text data format handler, or ToolboxItemCreatorCallback, to the toolbox. ToolboxItem 資料TextBox建立者回呼委派會將任何貼上的文字資料傳送至 [工具箱], 並將其拖曳至表單, 以建立包含文字的自訂。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.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Drawing;
using namespace System::Drawing::Design;
using namespace System::Windows::Forms;
using namespace System::Security::Permissions;

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

   public:
      TextToolboxItem( String^ text )
         : ToolboxItem()
      {
         this->text = text;
      }

   protected:

      // ToolboxItem::CreateComponentsCore  to create the TextBox
      // and link a method to set its Text property.

      virtual array<IComponent^>^ CreateComponentsCore( IDesignerHost^ host ) override
      {
         TextBox^ textbox = dynamic_cast<TextBox^>(host->CreateComponent( TextBox::typeid ));
         
         // 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 = dynamic_cast<Control^>(host->RootComponent);
         array<Object^>^temp0 = {textbox,text};
         c->BeginInvoke( gcnew SetTextMethodHandler( this, &TextToolboxItem::OnSetText ), temp0 );
         array<IComponent^>^temp1 = {textbox};
         return temp1;
      }

   private:

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

   };


   // 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.
   public ref class TextDataTextBoxComponent: public Component
   {
   private:
      bool creatorAdded;
      IToolboxService^ ts;

   public:
      TextDataTextBoxComponent()
      {
         creatorAdded = false;
      }


      property System::ComponentModel::ISite^ Site 
      {
         // ISite to register TextBox creator
         virtual System::ComponentModel::ISite^ get() override
         {
            return __super::Site;
         }

         virtual void set( System::ComponentModel::ISite^ value ) override
         {
            if ( value != nullptr )
            {
               __super::Site = value;
               if (  !creatorAdded )
                              AddTextTextBoxCreator();
            }
            else
            {
               if ( creatorAdded )
                              RemoveTextTextBoxCreator();
               __super::Site = value;
            }
         }
      }

   private:

      // Adds a "Text" data format creator to the toolbox that creates
      // a textbox from a text fragment pasted to the toolbox.
      void AddTextTextBoxCreator()
      {
         ts = dynamic_cast<IToolboxService^>(GetService( IToolboxService::typeid ));
         if ( ts != nullptr )
         {
            ToolboxItemCreatorCallback^ textCreator = 
				gcnew ToolboxItemCreatorCallback( 
				this, 
				&TextDataTextBoxComponent::CreateTextBoxForText );
            try
            {
               ts->AddCreator( 
				   textCreator, 
				   "Text", 
				   dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid )) );
               creatorAdded = true;
            }
            catch ( Exception^ ex ) 
            {
               MessageBox::Show( ex->ToString(), "Exception Information" );
            }
         }
      }


      // Removes any "Text" data format creator from the toolbox.
      void RemoveTextTextBoxCreator()
      {
         if ( ts != nullptr )
         {
            ts->RemoveCreator( 
				"Text", 
				dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid )) );
            creatorAdded = false;
         }
      }


      // ToolboxItemCreatorCallback delegate format method to create
      // the toolbox item.
      ToolboxItem^ CreateTextBoxForText( Object^ serializedObject, String^ format )
      {
		IDataObject^ o = gcnew DataObject(dynamic_cast<IDataObject^>(serializedObject));

		if( o->GetDataPresent("System::String", true) )
		{
			String^ toolboxText = dynamic_cast<String^>(o->GetData( "System::String", true ));
		   return( gcnew TextToolboxItem( toolboxText ));
		}

		return nullptr;
	  }

   public:
      ~TextDataTextBoxComponent()
      {
         if ( creatorAdded )
                  RemoveTextTextBoxCreator();
      }
   };
}
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;
        }
    }
}
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing
Imports System.Drawing.Design
Imports System.Security.Permissions
Imports System.Windows.Forms

' 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.
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
Public Class TextDataTextBoxComponent
    Inherits System.ComponentModel.Component

    Private creatorAdded As Boolean = False
    Private ts As IToolboxService

    Public Sub New()
    End Sub

    ' ISite override to register TextBox creator
    Public Overrides Property Site() As System.ComponentModel.ISite
        Get
            Return MyBase.Site
        End Get
        Set(ByVal Value As System.ComponentModel.ISite)
            If (Value IsNot Nothing) Then
                MyBase.Site = Value
                If Not creatorAdded Then
                    AddTextTextBoxCreator()
                End If
            Else
                If creatorAdded Then
                    RemoveTextTextBoxCreator()
                End If
                MyBase.Site = Value
            End If
        End Set
    End Property

    ' Adds a "Text" data format creator to the toolbox that creates 
    ' a textbox from a text fragment pasted to the toolbox.
    Private Sub AddTextTextBoxCreator()
        ts = CType(GetService(GetType(IToolboxService)), IToolboxService)
        If (ts IsNot Nothing) Then
            Dim textCreator As _
            New ToolboxItemCreatorCallback(AddressOf Me.CreateTextBoxForText)
            Try
                ts.AddCreator( _
                textCreator, _
                "Text", _
                CType(GetService(GetType(IDesignerHost)), IDesignerHost))

                creatorAdded = True
            Catch ex As Exception
                MessageBox.Show(ex.ToString(), "Exception Information")
            End Try
        End If
    End Sub

    ' Removes any "Text" data format creator from the toolbox.
    Private Sub RemoveTextTextBoxCreator()
        If (ts IsNot Nothing) Then
            ts.RemoveCreator( _
            "Text", _
            CType(GetService(GetType(IDesignerHost)), IDesignerHost))
            creatorAdded = False
        End If
    End Sub

    ' ToolboxItemCreatorCallback delegate format method to create 
    ' the toolbox item.
    Private Function CreateTextBoxForText( _
    ByVal serializedObject As Object, _
    ByVal format As String) As ToolboxItem

        Dim o As New DataObject(CType(serializedObject, IDataObject))

        Dim formats As String() = o.GetFormats()

        If o.GetDataPresent("System.String", True) Then

            Return New TextToolboxItem(CStr(o.GetData("System.String", True)))

        End If

        Return Nothing
    End Function

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If creatorAdded Then
            RemoveTextTextBoxCreator()
        End If
    End Sub

End Class

' Custom toolbox item creates a TextBox and sets its Text property
' to the constructor-specified text.
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
Public Class TextToolboxItem
    Inherits System.Drawing.Design.ToolboxItem

    Private [text] As String

    Delegate Sub SetTextMethodHandler( _
    ByVal c As Control, _
    ByVal [text] As String)

    Public Sub New(ByVal [text] As String)
        Me.text = [text]
    End Sub

    ' ToolboxItem.CreateComponentsCore override to create the TextBox 
    ' and link a method to set its Text property.
    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Protected Overrides Function CreateComponentsCore(ByVal host As IDesignerHost) As IComponent()
        Dim textbox As TextBox = CType(host.CreateComponent(GetType(TextBox)), TextBox)

        ' Because the designer resets the text of the textbox, use 
        ' a SetTextMethodHandler to set the text to the value of 
        ' the text data.
        Dim c As Control = host.RootComponent

        c.BeginInvoke( _
        New SetTextMethodHandler(AddressOf OnSetText), _
        New Object() {textbox, [text]})

        Return New System.ComponentModel.IComponent() {textbox}
    End Function

    ' Method to set the text property of a TextBox after it is initialized.
    Private Sub OnSetText(ByVal c As Control, ByVal [text] As String)
        c.Text = [text]
    End Sub

End Class

下列程式碼範例示範如何使用ToolboxItem類別做為自訂工具箱專案實作為基類。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);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Drawing.Design
Imports System.Runtime.Serialization
Imports System.Text
Imports System.Windows.Forms



Public Class Form1
    Inherits Form
    Private components As System.ComponentModel.IContainer = Nothing
    Friend WithEvents UserControl11 As UserControl1
    Friend WithEvents label1 As System.Windows.Forms.Label

    Public Sub New() 
        InitializeComponent()
    End Sub
    
    
    Private Sub InitializeComponent() 
        Me.label1 = New System.Windows.Forms.Label
        Me.UserControl11 = New UserControl1
        Me.SuspendLayout()
        '
        'label1
        '
        Me.label1.Location = New System.Drawing.Point(15, 16)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(265, 62)
        Me.label1.TabIndex = 0
        Me.label1.Text = "Build the project and drop UserControl1" + _
            " from the toolbox onto the form."
        '
        'UserControl11
        '
        Me.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."
        Me.UserControl11.Location = New System.Drawing.Point(74, 85)
        Me.UserControl11.Name = "UserControl11"
        Me.UserControl11.Padding = New System.Windows.Forms.Padding(6)
        Me.UserControl11.TabIndex = 1
        '
        'Form1
        '
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.UserControl11)
        Me.Controls.Add(Me.label1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
    End Sub
     
    
    Protected Overrides Sub Dispose(ByVal disposing As Boolean) 
        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub
    
    
    Shared Sub Main() 
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub
End Class

' Configure this user control to have a custom toolbox item.
<ToolboxItem(GetType(MyToolboxItem))> _
Public Class UserControl1
    Inherits UserControl
    Private components As System.ComponentModel.IContainer = Nothing
    Private label1 As System.Windows.Forms.Label


    Public Sub New()
        InitializeComponent()
    End Sub


    Public Property LabelText() As String
        Get
            Return label1.Text
        End Get
        Set(ByVal value As String)
            label1.Text = Value
        End Set
    End Property


    Private Sub InitializeComponent()
        Me.label1 = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        ' 
        ' label1
        ' 
        Me.label1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.label1.Location = New System.Drawing.Point(6, 6)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(138, 138)
        Me.label1.TabIndex = 0
        Me.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." + _
            vbCr + vbLf
        Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        ' 
        ' UserControl1
        ' 
        Me.Controls.Add(label1)
        Me.Name = "UserControl1"
        Me.Padding = New System.Windows.Forms.Padding(6)
        Me.ResumeLayout(False)
    End Sub


    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub
End Class

' Toolbox items must be serializable.
<Serializable()> _
Class MyToolboxItem
    Inherits ToolboxItem

    ' The add components dialog in Visual Studio looks for a public
    ' constructor that takes a type.
    Public Sub New(ByVal toolType As Type)
        MyBase.New(toolType)
    End Sub


    ' 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.  
    Sub New(ByVal info As SerializationInfo, _
        ByVal context As StreamingContext)
        Deserialize(info, context)
    End Sub


    ' Let's override the creation code and pop up a dialog.
    Protected Overrides Function CreateComponentsCore( _
        ByVal host As System.ComponentModel.Design.IDesignerHost, _
        ByVal defaultValues As System.Collections.IDictionary) _
        As IComponent()
        ' 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 d As New ToolboxItemDialog()
            If d.ShowDialog() = DialogResult.OK Then
                Dim [text] As String = d.CreationText
                Dim comps As IComponent() = _
                    MyBase.CreateComponentsCore(host, defaultValues)
                ' comps will have a single component: our data type.
                CType(comps(0), UserControl1).LabelText = [text]
                Return comps
            Else
                Return Nothing
            End If
        End Using
    End Function
End Class


Public Class ToolboxItemDialog
    Inherits Form
    Private components As System.ComponentModel.IContainer = Nothing
    Private label1 As System.Windows.Forms.Label
    Private textBox1 As System.Windows.Forms.TextBox
    Private button1 As System.Windows.Forms.Button
    Private button2 As System.Windows.Forms.Button
    
    
    Public Sub New() 
        InitializeComponent()
    End Sub
    
    Private Sub InitializeComponent() 
        Me.label1 = New System.Windows.Forms.Label()
        Me.textBox1 = New System.Windows.Forms.TextBox()
        Me.button1 = New System.Windows.Forms.Button()
        Me.button2 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        ' 
        ' label1
        ' 
        Me.label1.Location = New System.Drawing.Point(10, 9)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(273, 43)
        Me.label1.TabIndex = 0
        Me.label1.Text = "Enter the text you would like" + _
            " to have the user control populated with:"
        ' 
        ' textBox1
        ' 
        Me.textBox1.AutoSize = False
        Me.textBox1.Location = New System.Drawing.Point(10, 58)
        Me.textBox1.Multiline = True
        Me.textBox1.Name = "textBox1"
        Me.textBox1.Size = New System.Drawing.Size(270, 67)
        Me.textBox1.TabIndex = 1
        Me.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
        ' 
        Me.button1.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.button1.Location = New System.Drawing.Point(124, 131)
        Me.button1.Name = "button1"
        Me.button1.TabIndex = 2
        Me.button1.Text = "OK"
        ' 
        ' button2
        ' 
        Me.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.button2.Location = New System.Drawing.Point(205, 131)
        Me.button2.Name = "button2"
        Me.button2.TabIndex = 3
        Me.button2.Text = "Cancel"
        ' 
        ' ToolboxItemDialog
        ' 
        Me.AcceptButton = Me.button1
        Me.CancelButton = Me.button2
        Me.ClientSize = New System.Drawing.Size(292, 162)
        Me.ControlBox = False
        Me.Controls.Add(button2)
        Me.Controls.Add(button1)
        Me.Controls.Add(textBox1)
        Me.Controls.Add(label1)
        Me.FormBorderStyle = _
            System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Name = "ToolboxItemDialog"
        Me.Text = "ToolboxItemDialog"
        Me.ResumeLayout(False)
    
    End Sub
    
    Public ReadOnly Property CreationText() As String 
        Get
            Return textBox1.Text
        End Get
    End Property
    
    
    Protected Overrides Sub Dispose(ByVal disposing As Boolean) 
        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    
    End Sub
End Class

備註

ToolboxItem是工具箱專案的基類, 可以在設計階段環境的 [工具箱] 中顯示。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. ToolboxItem類別會提供所需的方法和屬性, 以提供工具箱專案的顯示內容、在使用時建立元件或元件, 以及在工具箱中序列化和還原序列化本身以進行持續性資料.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.

您可以使用要ToolboxItem建立的名稱、點陣圖和類型來設定類別的實例, 而不需要建立衍生自ToolboxItem的類別。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. ToolboxItem類別也會提供自訂工具箱專案實作為基底類別。The ToolboxItem class also provides a base class for custom toolbox item implementations. 自訂ToolboxItem可以建立多個元件。A custom ToolboxItem can create multiple components. 若要執行自訂工具箱專案, 您必須從ToolboxItem衍生CreateComponentsCore, 並覆Serialize寫、 Deserialize和方法。To implement a custom toolbox item, you must derive from ToolboxItem and override the CreateComponentsCore, Serialize, and Deserialize methods.

下列屬性和方法必須設定為ToolboxItem , 才能正確運作:The following properties and methods must be configured for a ToolboxItem to function correctly:

  • DisplayName屬性會在 [工具箱] 中顯示 [工具箱] 專案時指定其標籤。The DisplayName property specifies the label for the toolbox item when displayed in a toolbox.

  • TypeName屬性會指定專案所建立之元件類型的完整名稱。The TypeName property specifies the fully qualified name of the type of the component that the item creates. 如果衍生類別建立多個元件, 則TypeName不一定會使用屬性, 而是根據CreateComponentsCore方法覆寫是否取決於這個屬性的值而定。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.

  • AssemblyName屬性會指定包含專案所建立之元件類型的元件。The AssemblyName property specifies the assembly that contains the type of a component that the item creates.

  • Bitmap屬性可選擇性地指定要顯示在 [工具箱] 中 [工具箱] 專案之顯示名稱旁邊的點陣圖影像。The Bitmap property optionally specifies a bitmap image to display next to the display name for the toolbox item in the toolbox.

  • 屬性會選擇性地包含ToolboxItemFilterAttribute任何物件, 以決定是否可以在特定元件上使用 [工具箱] 專案。 FilterThe Filter property optionally contains any ToolboxItemFilterAttribute objects that determine whether the toolbox item can be used on a particular component.

  • CreateComponentsCore方法會傳回要在使用此工具的位置插入的元件實例。The CreateComponentsCore method returns the component instance or instances to insert where this tool is used.

  • 方法會將 [工具箱] 專案儲存至SerializationInfo指定的。 SerializeThe Serialize method saves the toolbox item to a specified SerializationInfo.

  • 方法會從指定SerializationInfo之所包含的狀態資訊設定工具箱專案。 DeserializeThe Deserialize method configures the toolbox item from the state information contained in the specified SerializationInfo.

  • 如果尚未覆寫Initialize 方法來以不同方式運作,方法會將工具箱專案設定為建立指定的元件類型。CreateComponentsCoreThe Initialize method configures the toolbox item to create the specified type of component, if the CreateComponentsCore method has not been overridden to behave differently.

  • Locked屬性會指出 [工具箱] 專案的屬性是否可以變更。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.

  • Lock方法會鎖定工具箱專案。The Lock method locks a toolbox item.

  • 如果屬性為, 則CheckUnlocked方法會true擲回例外狀況。 LockedThe CheckUnlocked method throws an exception if the Locked property is true.

建構函式

ToolboxItem() ToolboxItem() ToolboxItem() ToolboxItem()

初始化 ToolboxItem 類別的新執行個體。Initializes a new instance of the ToolboxItem class.

ToolboxItem(Type) ToolboxItem(Type) ToolboxItem(Type) ToolboxItem(Type)

初始化 ToolboxItem 類別的新執行個體,以建立元件的指定型別。Initializes a new instance of the ToolboxItem class that creates the specified type of component.

屬性

AssemblyName AssemblyName AssemblyName AssemblyName

取得或設定組件的名稱,該組件包含類型或工具箱項目所建立的類型。Gets or sets the name of the assembly that contains the type or types that the toolbox item creates.

Bitmap Bitmap Bitmap Bitmap

取得或設定點陣圖,表示工具箱中的工具箱項目。Gets or sets a bitmap to represent the toolbox item in the toolbox.

Company Company Company Company

取得或設定這個 ToolboxItem 的公司名稱。Gets or sets the company name for this ToolboxItem.

ComponentType ComponentType ComponentType ComponentType

取得這個 ToolboxItem 的元件型別。Gets the component type for this ToolboxItem.

DependentAssemblies DependentAssemblies DependentAssemblies DependentAssemblies

取得或設定工具箱項目的 AssemblyNameGets or sets the AssemblyName for the toolbox item.

Description Description Description Description

取得或設定這個 ToolboxItem 的描述。Gets or sets the description for this ToolboxItem.

DisplayName DisplayName DisplayName DisplayName

取得或設定工具箱項目的顯示名稱。Gets or sets the display name for the toolbox item.

Filter Filter Filter Filter

取得或設定篩選條件,判斷工具箱項目是否可以在目的元件上使用。Gets or sets the filter that determines whether the toolbox item can be used on a destination component.

IsTransient IsTransient IsTransient IsTransient

取得值,指出工具箱項目是否為暫時性 (Transient)。Gets a value indicating whether the toolbox item is transient.

Locked Locked Locked Locked

取得值,指出 ToolboxItem 目前是否已鎖定。Gets a value indicating whether the ToolboxItem is currently locked.

OriginalBitmap OriginalBitmap OriginalBitmap OriginalBitmap

取得或設定此項目工具箱中將使用的原始點陣圖。Gets or sets the original bitmap that will be used in the toolbox for this item.

Properties Properties Properties Properties

取得屬性的字典。Gets a dictionary of properties.

TypeName TypeName TypeName TypeName

取得或設定叫用工具箱項目時所建立的 IComponent 的型別完整名稱。Gets or sets the fully qualified name of the type of IComponent that the toolbox item creates when invoked.

Version Version Version Version

取得這個 ToolboxItem 的版本。Gets the version for this ToolboxItem.

方法

CheckUnlocked() CheckUnlocked() CheckUnlocked() CheckUnlocked()

如果工具箱項目目前是鎖定的,則會擲回例外狀況。Throws an exception if the toolbox item is currently locked.

CreateComponents() CreateComponents() CreateComponents() CreateComponents()

建立工具箱項目受到設定要建立的元件。Creates the components that the toolbox item is configured to create.

CreateComponents(IDesignerHost) CreateComponents(IDesignerHost) CreateComponents(IDesignerHost) CreateComponents(IDesignerHost)

使用指定的設計工具主應用程式 (Designer Host),建立工具箱項目受到設定要建立的元件。Creates the components that the toolbox item is configured to create, using the specified designer host.

CreateComponents(IDesignerHost, IDictionary) CreateComponents(IDesignerHost, IDictionary) CreateComponents(IDesignerHost, IDictionary) CreateComponents(IDesignerHost, IDictionary)

使用指定的設計工具主應用程式 (Designer Host) 和預設值,建立工具箱項目設定為要建立的元件。Creates the components that the toolbox item is configured to create, using the specified designer host and default values.

CreateComponentsCore(IDesignerHost) CreateComponentsCore(IDesignerHost) CreateComponentsCore(IDesignerHost) CreateComponentsCore(IDesignerHost)

建立元件或叫用工具箱項目時要使用之元件的陣列。Creates a component or an array of components when the toolbox item is invoked.

CreateComponentsCore(IDesignerHost, IDictionary) CreateComponentsCore(IDesignerHost, IDictionary) CreateComponentsCore(IDesignerHost, IDictionary) CreateComponentsCore(IDesignerHost, IDictionary)

在叫用工具箱項目時建立元件陣列。Creates an array of components when the toolbox item is invoked.

Deserialize(SerializationInfo, StreamingContext) Deserialize(SerializationInfo, StreamingContext) Deserialize(SerializationInfo, StreamingContext) Deserialize(SerializationInfo, StreamingContext)

從指定的序列化資訊物件載入工具箱項目的狀態。Loads the state of the toolbox item from the specified serialization information object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷兩個 ToolboxItem 執行個體是否相等。Determines whether two ToolboxItem instances are equal.

FilterPropertyValue(String, Object) FilterPropertyValue(String, Object) FilterPropertyValue(String, Object) FilterPropertyValue(String, Object)

在傳回前篩選屬性值。Filters a property value before returning it.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
GetType(IDesignerHost) GetType(IDesignerHost) GetType(IDesignerHost) GetType(IDesignerHost)

啟用對與工具箱項目關聯之類型的存取。Enables access to the type associated with the toolbox item.

GetType(IDesignerHost, AssemblyName, String, Boolean) GetType(IDesignerHost, AssemblyName, String, Boolean) GetType(IDesignerHost, AssemblyName, String, Boolean) GetType(IDesignerHost, AssemblyName, String, Boolean)

建立指定類型的執行個體,並選擇性使用指定的設計工具主應用程式和組件名稱。Creates an instance of the specified type, optionally using a specified designer host and assembly name.

Initialize(Type) Initialize(Type) Initialize(Type) Initialize(Type)

使用要建立的指定類型來初始化目前工具箱項目。Initializes the current toolbox item with the specified type to create.

Lock() Lock() Lock() Lock()

鎖定工具箱項目並防止變更其屬性。Locks the toolbox item and prevents changes to its properties.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
OnComponentsCreated(ToolboxComponentsCreatedEventArgs) OnComponentsCreated(ToolboxComponentsCreatedEventArgs) OnComponentsCreated(ToolboxComponentsCreatedEventArgs) OnComponentsCreated(ToolboxComponentsCreatedEventArgs)

引發 ComponentsCreated 事件。Raises the ComponentsCreated event.

OnComponentsCreating(ToolboxComponentsCreatingEventArgs) OnComponentsCreating(ToolboxComponentsCreatingEventArgs) OnComponentsCreating(ToolboxComponentsCreatingEventArgs) OnComponentsCreating(ToolboxComponentsCreatingEventArgs)

引發 ComponentsCreating 事件。Raises the ComponentsCreating event.

Serialize(SerializationInfo, StreamingContext) Serialize(SerializationInfo, StreamingContext) Serialize(SerializationInfo, StreamingContext) Serialize(SerializationInfo, StreamingContext)

將工具箱項目的狀態儲存到指定的序列化資訊物件。Saves the state of the toolbox item to the specified serialization information object.

ToString() ToString() ToString() ToString()

傳回表示目前 StringToolboxItemReturns a String that represents the current ToolboxItem.

ValidatePropertyType(String, Object, Type, Boolean) ValidatePropertyType(String, Object, Type, Boolean) ValidatePropertyType(String, Object, Type, Boolean) ValidatePropertyType(String, Object, Type, Boolean)

驗證物件是否為指定類型。Validates that an object is of a given type.

ValidatePropertyValue(String, Object) ValidatePropertyValue(String, Object) ValidatePropertyValue(String, Object) ValidatePropertyValue(String, Object)

將屬性指派給屬性字典前驗證屬性。Validates a property before it is assigned to the property dictionary.

事件

ComponentsCreated ComponentsCreated ComponentsCreated ComponentsCreated

立即發生於建立元件之後。Occurs immediately after components are created.

ComponentsCreating ComponentsCreating ComponentsCreating ComponentsCreating

發生於即將建立元件時。Occurs when components are about to be created.

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

如需這個成員的描述,請參閱 GetObjectData(SerializationInfo, StreamingContext) 方法。For a description of this member, see the GetObjectData(SerializationInfo, StreamingContext) method.

安全性

NamedPermissionSet
以取得系統資源的完整存取權。for full access to system resources. 需求值: LinkDemandInheritanceDemandDemand values: LinkDemand, InheritanceDemand. 相關聯的狀態:Associated state:

適用於

另請參閱