ToolboxItem 클래스

정의

기본 구현된 도구 상자 항목을 제공합니다.

public ref class ToolboxItem : System::Runtime::Serialization::ISerializable
[System.Serializable]
public class ToolboxItem : System.Runtime.Serialization.ISerializable
public class ToolboxItem : System.Runtime.Serialization.ISerializable
[<System.Serializable>]
type ToolboxItem = class
    interface ISerializable
type ToolboxItem = class
    interface ISerializable
Public Class ToolboxItem
Implements ISerializable
상속
ToolboxItem
파생
특성
구현

예제

다음 코드 예제에서는 인터페이스를 사용하여 IToolboxService 도구 상자에 텍스트 데이터 형식 처리기 또는 ToolboxItemCreatorCallback를 추가하는 구성 요소를 제공합니다. 데이터 작성자 콜백 대리자는 도구 상자에 붙여넣은 모든 텍스트 데이터를 전달하고 텍스트를 포함하는 을 TextBox 만드는 사용자 지정 ToolboxItem 으로 폼으로 끌어옵니다.

#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.
    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.
    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.
        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.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 하는 방법을 보여 줍니다.

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.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 도구 상자 항목에 대한 표시 속성을 도구 상자에 제공하고, 사용할 때 구성 요소 또는 구성 요소를 만들고, 도구 상자 데이터베이스 내에서 지속성을 위해 자신을 직렬화 및 역직렬화하는 데 필요한 메서드 및 속성을 제공합니다.

클래스의 ToolboxItem instance 에서 파생ToolboxItem되는 클래스를 만들지 않고 만들 이름, 비트맵 및 형식으로 구성할 수 있습니다. 또한 클래스는 ToolboxItem 사용자 지정 도구 상자 항목 구현을 위한 기본 클래스를 제공합니다. 사용자 지정 ToolboxItem 은 여러 구성 요소를 만들 수 있습니다. 사용자 지정 도구 상자 항목을 구현하려면 에서 ToolboxItem 파생되고 , SerializeDeserialize 메서드를 재정의CreateComponentsCore해야 합니다.

가 올바르게 작동하려면 다음 속성과 메서드를 ToolboxItem 구성해야 합니다.

  • 속성은 DisplayName 도구 상자에 표시될 때 도구 상자 항목의 레이블을 지정합니다.

  • 속성은 TypeName 항목이 만드는 구성 요소 형식의 정규화된 이름을 지정합니다. 파생 클래스가 여러 구성 요소를 TypeName 만드는 경우 메서드 재정의가 이 속성의 값에 따라 달라지는지 여부에 CreateComponentsCore 따라 속성이 사용될 수도 있거나 사용되지 않을 수도 있습니다.

  • 속성은 AssemblyName 항목이 만드는 구성 요소의 형식을 포함하는 어셈블리를 지정합니다.

  • 속성은 Bitmap 필요에 따라 도구 상자에서 도구 상자 항목의 표시 이름 옆에 표시할 비트맵 이미지를 지정합니다.

  • 속성은 Filter 필요에 따라 도구 상자 항목을 특정 구성 요소에서 사용할 수 있는지 여부를 결정 하는 개체 ToolboxItemFilterAttribute 를 포함 합니다.

  • 메서드는 CreateComponentsCore 이 도구가 사용되는 위치를 삽입할 구성 요소 instance 또는 인스턴스를 반환합니다.

  • 메서드는 Serialize 도구 상자 항목을 지정된 SerializationInfo에 저장합니다.

  • 메서드는 Deserialize 지정된 SerializationInfo에 포함된 상태 정보에서 도구 상자 항목을 구성합니다.

  • 메서드가 Initialize 다르게 동작하도록 재정의되지 않은 경우 CreateComponentsCore 메서드는 지정된 유형의 구성 요소를 만들도록 도구 상자 항목을 구성합니다.

  • 속성은 Locked 도구 상자 항목의 속성을 변경할 수 있는지 여부를 나타냅니다. 도구 상자 항목은 일반적으로 도구 상자에 추가된 후 잠깁니다.

  • 메서드는 Lock 도구 상자 항목을 잠가줍니다.

  • 메서드는 CheckUnlocked 속성이 인 경우 예외를 Locked throw합니다 true.

생성자

ToolboxItem()

ToolboxItem 클래스의 새 인스턴스를 초기화합니다.

ToolboxItem(Type)

지정된 구성 요소 형식을 만드는 ToolboxItem 클래스의 새 인스턴스를 초기화합니다.

속성

AssemblyName

도구 상자 항목이 만드는 형식을 포함하는 어셈블리 이름을 가져오거나 설정합니다.

Bitmap

도구 상자에서 도구 상자 항목을 나타내는 비트맵을 가져오거나 설정합니다.

Company

ToolboxItem의 회사 이름을 가져오거나 설정합니다.

ComponentType

ToolboxItem에 대한 구성 요소 형식을 가져옵니다.

DependentAssemblies

도구 상자 항목의 AssemblyName을 가져오거나 설정합니다.

Description

ToolboxItem의 설명을 가져오거나 설정합니다.

DisplayName

도구 상자 항목의 표시 이름을 가져오거나 설정합니다.

Filter

도구 상자 항목이 대상 구성 요소에서 사용될 수 있는지를 결정하는 필터를 가져오거나 설정합니다.

IsTransient

도구 상자 항목이 임시인지를 나타내는 값을 가져옵니다.

Locked

ToolboxItem이 현재 잠겨 있는지 여부를 나타내는 값을 가져옵니다.

OriginalBitmap

이 항목의 도구 상자에서 사용될 원래 비트맵을 가져오거나 설정합니다.

Properties

속성 사전을 가져옵니다.

TypeName

도구 상자 항목이 호출될 때 만드는 IComponent 형식의 정규화된 이름을 가져오거나 설정합니다.

Version

ToolboxItem의 버전을 가져옵니다.

메서드

CheckUnlocked()

도구 상자 항목이 현재 잠겨 있으면 예외를 throw합니다.

CreateComponents()

도구 상자 항목이 만들도록 구성된 구성 요소를 만듭니다.

CreateComponents(IDesignerHost)

도구 상자 항목이 만들도록 구성된 구성 요소를 지정된 디자이너 호스트를 사용하여 만듭니다.

CreateComponents(IDesignerHost, IDictionary)

도구 상자 항목이 만들도록 구성된 구성 요소를 지정된 디자이너 호스트와 기본값을 사용하여 만듭니다.

CreateComponentsCore(IDesignerHost)

도구 상자 항목이 호출될 때 구성 요소 한 개나 구성 요소의 배열을 만듭니다.

CreateComponentsCore(IDesignerHost, IDictionary)

도구 상자 항목이 호출될 때 구성 요소의 배열을 만듭니다.

Deserialize(SerializationInfo, StreamingContext)

도구 상자 항목의 상태를 지정된 serialization 정보 개체에서 로드합니다.

Equals(Object)

두 개의 ToolboxItem 인스턴스가 같은지 여부를 확인합니다.

FilterPropertyValue(String, Object)

속성 값을 반환하기 전에 필터링합니다.

GetHashCode()

이 인스턴스의 해시 코드를 반환합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
GetType(IDesignerHost)

도구 상자 항목과 연결된 형식에 대한 액세스를 가능하게 합니다.

GetType(IDesignerHost, AssemblyName, String, Boolean)

지정된 디자이너 호스트와 어셈블리 이름을 선택적으로 사용하여 지정된 형식의 인스턴스를 만듭니다.

Initialize(Type)

만들려는 지정된 형식으로 현재 도구 상자 항목을 초기화합니다.

Lock()

도구 상자 항목을 잠그고 속성에 대한 변경을 방지합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
OnComponentsCreated(ToolboxComponentsCreatedEventArgs)

ComponentsCreated 이벤트를 발생시킵니다.

OnComponentsCreating(ToolboxComponentsCreatingEventArgs)

ComponentsCreating 이벤트를 발생시킵니다.

Serialize(SerializationInfo, StreamingContext)

도구 상자 항목의 상태를 지정된 serialization 정보 개체에 저장합니다.

ToString()

현재 ToolboxItem를 나타내는 String을 반환합니다.

ValidatePropertyType(String, Object, Type, Boolean)

개체가 지정된 형식인지 유효성을 검사합니다.

ValidatePropertyValue(String, Object)

속성을 속성 사전에 할당하기 전에 유효성을 검사합니다.

이벤트

ComponentsCreated

구성 요소를 만든 후 즉시 발생합니다.

ComponentsCreating

구성 요소를 만들기 직전에 발생합니다.

명시적 인터페이스 구현

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

이 멤버에 대한 설명을 보려면 GetObjectData(SerializationInfo, StreamingContext) 메서드를 참조하세요.

적용 대상

추가 정보