IToolboxService Интерфейс

Определение

Обеспечивает методы и свойства для управления панелью инструментов в среде разработки и выполнения запросов к этой панели.

public interface class IToolboxService
[System.Runtime.InteropServices.Guid("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76")]
[System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IToolboxService
[<System.Runtime.InteropServices.Guid("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76")>]
[<System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)>]
type IToolboxService = interface
Public Interface IToolboxService
Производный
Атрибуты

Примеры

В следующем примере кода демонстрируется использование в режиме конструктора IToolboxService для перечисления и выбора категорий и элементов панели элементов, а также для создания компонентов или элементов управления из элементов панели элементов и добавления их в Form. Чтобы использовать пример, скомпилируйте код в сборку и добавьте ссылку на сборку в Windows Forms приложении. Если вы используете Visual Studio, IToolboxServiceControl объект автоматически добавляется на панель элементов. Создайте экземпляр в IToolboxServiceControl форме, чтобы проверить его поведение.

#using <System.dll>
#using <System.Design.dll>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>
#using <System.Drawing.dll>

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

namespace IToolboxServiceExample
{

   // This designer passes window messages to the controls at design time.
   public ref class WindowMessageDesigner: public System::Windows::Forms::Design::ControlDesigner
   {
   public:
      WindowMessageDesigner(){}

   protected:

      // Window procedure  passes events to control.

      [SecurityPermission(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)]
      virtual void WndProc( System::Windows::Forms::Message% m ) override
      {
         if ( m.HWnd == this->Control->Handle )
                  ControlDesigner::WndProc( m );
         else
                  ControlDesigner::DefWndProc( m );
      }
   };

   // Provides an example control that functions in design mode to
   // demonstrate use of the IToolboxService to list and select toolbox
   // categories and items, and to add components or controls
   // to the parent form using code.

   [DesignerAttribute(IToolboxServiceExample::WindowMessageDesigner::typeid,IDesigner::typeid)]
   public ref class IToolboxServiceControl: public System::Windows::Forms::UserControl
   {
   private:
      System::Windows::Forms::ListBox^ listBox1;
      System::Windows::Forms::ListBox^ listBox2;
      IToolboxService^ toolboxService;
      ToolboxItemCollection^ tools;
      int controlSpacingMultiplier;

   public:
      IToolboxServiceControl()
      {
         InitializeComponent();
         listBox2->DoubleClick += gcnew EventHandler( this, &IToolboxServiceControl::CreateComponent );
         controlSpacingMultiplier = 0;
      }

      property System::ComponentModel::ISite^ Site 
      {
         // Obtain or reset IToolboxService reference on each siting of control.
         virtual System::ComponentModel::ISite^ get() override
         {
            return __super::Site;
         }

         virtual void set( System::ComponentModel::ISite^ value ) override
         {
            __super::Site = value;

            // If the component was sited, attempt to obtain
            // an IToolboxService instance.
            if ( __super::Site != nullptr )
            {
               toolboxService = dynamic_cast<IToolboxService^>(this->GetService( IToolboxService::typeid ));

               // If an IToolboxService was located, update the
               // category list.
               if ( toolboxService != nullptr )
                              UpdateLists();
            }
            else
                        toolboxService = nullptr;
         }
      }

   private:

      // Updates the list of categories and the list of items in the
      // selected category.
      [SecurityPermission(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)]
      void UpdateLists()
      {
         if ( toolboxService != nullptr )
         {
            this->listBox1->SelectedIndexChanged -= gcnew System::EventHandler( this, &IToolboxServiceControl::UpdateSelectedCategory );
            this->listBox2->SelectedIndexChanged -= gcnew System::EventHandler( this, &IToolboxServiceControl::UpdateSelectedItem );
            listBox1->Items->Clear();
            for ( int i = 0; i < toolboxService->CategoryNames->Count; i++ )
            {
               listBox1->Items->Add( toolboxService->CategoryNames[ i ] );
               if ( toolboxService->CategoryNames[ i ] == toolboxService->SelectedCategory )
               {
                  listBox1->SelectedIndex = i;
                  tools = toolboxService->GetToolboxItems( toolboxService->SelectedCategory );
                  listBox2->Items->Clear();
                  for ( int j = 0; j < tools->Count; j++ )
                     listBox2->Items->Add( tools[ j ]->DisplayName );
               }
            }
            this->listBox1->SelectedIndexChanged += gcnew System::EventHandler( this, &IToolboxServiceControl::UpdateSelectedCategory );
            this->listBox2->SelectedIndexChanged += gcnew System::EventHandler( this, &IToolboxServiceControl::UpdateSelectedItem );
         }
      }


      // Sets the selected category when a category is clicked in the
      // category list.
      void UpdateSelectedCategory( Object^ /*sender*/, System::EventArgs^ /*e*/ )
      {
         if ( toolboxService != nullptr )
         {
            toolboxService->SelectedCategory = dynamic_cast<String^>(listBox1->SelectedItem);
            UpdateLists();
         }
      }

      // Sets the selected item when an item is clicked in the item list.
      void UpdateSelectedItem( Object^ /*sender*/, System::EventArgs^ /*e*/ )
      {
         if ( toolboxService != nullptr )
         {
            if ( listBox1->SelectedIndex != -1 )
            {
               if ( dynamic_cast<String^>(listBox1->SelectedItem) == toolboxService->SelectedCategory )
                              toolboxService->SetSelectedToolboxItem( tools[ listBox2->SelectedIndex ] );
               else
                              UpdateLists();
            }
         }
      }

      // Creates a control from a double-clicked toolbox item and adds
      // it to the parent form.
      void CreateComponent( Object^ /*sender*/, EventArgs^ /*e*/ )
      {
         // Obtains an IDesignerHost service from design environment.
         IDesignerHost^ host = dynamic_cast<IDesignerHost^>(this->GetService( IDesignerHost::typeid ));

         // Get the project components container (Windows Forms control
         // containment depends on controls collections).
         IContainer^ container = host->Container;

         // Identifies the parent Form.
         System::Windows::Forms::Form^ parentForm = this->FindForm();

         // Retrieves the parent Form's designer host.
         IDesignerHost^ parentHost = dynamic_cast<IDesignerHost^>(parentForm->Site->GetService( IDesignerHost::typeid ));

         // Create the components.
         array<IComponent^>^comps = nullptr;
         try
         {
            comps = toolboxService->GetSelectedToolboxItem()->CreateComponents( parentHost );
         }
         catch ( Exception^ ex ) 
         {
            // Catch and show any exceptions to prevent disabling
            // the control's UI.
            MessageBox::Show( ex->ToString(), "Exception message" );
         }

         if ( comps == nullptr )
                  return;

         // Add any created controls to the parent form's controls
         // collection. Note: components are added from the
         // ToolboxItem::CreateComponents(IDesignerHost*) method.
         for ( int i = 0; i < comps->Length; i++ )
         {
            if ( parentForm != nullptr && comps[ i ]->GetType()->IsSubclassOf( System::Windows::Forms::Control::typeid ) )
            {
               (dynamic_cast<System::Windows::Forms::Control^>(comps[ i ]))->Location = Point(20 * controlSpacingMultiplier,20 * controlSpacingMultiplier);
               if ( controlSpacingMultiplier > 10 )
                              controlSpacingMultiplier = 0;
               else
                              controlSpacingMultiplier++;
               parentForm->Controls->Add( dynamic_cast<System::Windows::Forms::Control^>(comps[ i ]) );
            }
         }
      }

   protected:

      // Displays labels.
      virtual void OnPaint( System::Windows::Forms::PaintEventArgs^ e ) override
      {
         e->Graphics->DrawString( "IToolboxService Control", gcnew System::Drawing::Font( "Arial",14 ), gcnew SolidBrush( Color::Black ), 6, 4 );
         e->Graphics->DrawString( "Category List", gcnew System::Drawing::Font( "Arial",8 ), gcnew SolidBrush( Color::Black ), 8, 26 );
         e->Graphics->DrawString( "Items in Category", gcnew System::Drawing::Font( "Arial",8 ), gcnew SolidBrush( Color::Black ), 208, 26 );
         e->Graphics->DrawString( "(Double-click item to add to parent form)", gcnew System::Drawing::Font( "Arial",7 ), gcnew SolidBrush( Color::Black ), 232, 12 );
      }

   private:
      void InitializeComponent()
      {
         this->listBox1 = gcnew System::Windows::Forms::ListBox;
         this->listBox2 = gcnew System::Windows::Forms::ListBox;
         this->SuspendLayout();
         this->listBox1->Anchor = static_cast<AnchorStyles>(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left);
         this->listBox1->Location = System::Drawing::Point( 8, 41 );
         this->listBox1->Name = "listBox1";
         this->listBox1->Size = System::Drawing::Size( 192, 368 );
         this->listBox1->TabIndex = 0;
         this->listBox1->SelectedIndexChanged += gcnew System::EventHandler( this, &IToolboxServiceControl::UpdateSelectedCategory );
         this->listBox2->Anchor = static_cast<AnchorStyles>(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left | System::Windows::Forms::AnchorStyles::Right);
         this->listBox2->Location = System::Drawing::Point( 208, 41 );
         this->listBox2->Name = "listBox2";
         this->listBox2->Size = System::Drawing::Size( 228, 368 );
         this->listBox2->TabIndex = 3;
         this->BackColor = System::Drawing::Color::Beige;
         array<System::Windows::Forms::Control^>^temp0 = {this->listBox2,this->listBox1};
         this->Controls->AddRange( temp0 );
         this->Location = System::Drawing::Point( 500, 400 );
         this->Name = "IToolboxServiceControl*";
         this->Size = System::Drawing::Size( 442, 422 );
         this->ResumeLayout( false );
      }
   };
}
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;

namespace IToolboxServiceExample
{	
    // Provides an example control that functions in design mode to 
    // demonstrate use of the IToolboxService to list and select toolbox 
    // categories and items, and to add components or controls 
    // to the parent form using code.
    [DesignerAttribute(typeof(WindowMessageDesigner), typeof(IDesigner))]
    public class IToolboxServiceControl : System.Windows.Forms.UserControl
    {		
        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.ListBox listBox2;
        private IToolboxService toolboxService = null;
        private ToolboxItemCollection tools;
        private int controlSpacingMultiplier;

        public IToolboxServiceControl()
        {
            InitializeComponent();
            listBox2.DoubleClick += new EventHandler(this.CreateComponent);
            controlSpacingMultiplier = 0;
        }
        
        // Obtain or reset IToolboxService reference on each siting of control.
        public override System.ComponentModel.ISite Site
        {
            get
            {
                return base.Site;
            }
            set
            {     
                base.Site = value;

                // If the component was sited, attempt to obtain 
                // an IToolboxService instance.
                if( base.Site != null )
                {
                    toolboxService = (IToolboxService)this.GetService(typeof(IToolboxService));
                    // If an IToolboxService was located, update the 
                    // category list.
                    if( toolboxService != null )
                        UpdateLists();                    
                }
                else
                {
                    toolboxService = null;
                }
            }
        }

        // Updates the list of categories and the list of items in the 
        // selected category.
        private void UpdateLists()
        {
            if( toolboxService != null )
            {
                this.listBox1.SelectedIndexChanged -= new System.EventHandler(this.UpdateSelectedCategory);
                this.listBox2.SelectedIndexChanged -= new System.EventHandler(this.UpdateSelectedItem);
                listBox1.Items.Clear();
                for( int i=0; i<toolboxService.CategoryNames.Count; i++ )
                {
                    listBox1.Items.Add( toolboxService.CategoryNames[i] );
                    if( toolboxService.CategoryNames[i] == toolboxService.SelectedCategory )
                    {
                        listBox1.SelectedIndex = i;                        
                        tools = toolboxService.GetToolboxItems( toolboxService.SelectedCategory );
                        listBox2.Items.Clear();
                        for( int j=0; j<tools.Count; j++ )
                            listBox2.Items.Add( tools[j].DisplayName );
                    }
                }
                this.listBox1.SelectedIndexChanged += new System.EventHandler(this.UpdateSelectedCategory);
                this.listBox2.SelectedIndexChanged += new System.EventHandler(this.UpdateSelectedItem);
            }
        }

        // Sets the selected category when a category is clicked in the 
        // category list.
        private void UpdateSelectedCategory(object sender, System.EventArgs e)
        {
            if( toolboxService != null )
            {
                toolboxService.SelectedCategory = (string)listBox1.SelectedItem;
                UpdateLists();
            }
        }

        // Sets the selected item when an item is clicked in the item list.
        private void UpdateSelectedItem(object sender, System.EventArgs e)
        {
            if( toolboxService != null )      
            {
                if( listBox1.SelectedIndex != -1 )
                {
                    if( (string)listBox1.SelectedItem == toolboxService.SelectedCategory )
                        toolboxService.SetSelectedToolboxItem(tools[listBox2.SelectedIndex]);  
                    else
                        UpdateLists();
                }
            }            
        }   

        // Creates a control from a double-clicked toolbox item and adds 
        // it to the parent form.
        private void CreateComponent(object sender, EventArgs e)
        {
            // Obtains an IDesignerHost service from design environment.
            IDesignerHost host = (IDesignerHost)this.GetService(typeof(IDesignerHost));

            // Get the project components container (Windows Forms control 
            // containment depends on controls collections).
            IContainer container = host.Container;
                        
            // Identifies the parent Form.
            System.Windows.Forms.Form parentForm = this.FindForm();

            // Retrieves the parent Form's designer host.
            IDesignerHost parentHost = (IDesignerHost)parentForm.Site.GetService(typeof(IDesignerHost));

            // Create the components.
            IComponent[] comps = null;
            try
            {
                 comps = toolboxService.GetSelectedToolboxItem().CreateComponents(parentHost);
            }
            catch(Exception ex)
            {
                // Catch and show any exceptions to prevent disabling 
                // the control's UI.
                MessageBox.Show(ex.ToString(), "Exception message");
            }
            if( comps == null )
                return;

            // Add any created controls to the parent form's controls 
            // collection. Note: components are added from the 
            // ToolboxItem.CreateComponents(IDesignerHost) method.
            for( int i=0; i<comps.Length; i++ )            
            {
                if( parentForm!= null && comps[i].GetType().IsSubclassOf(typeof(System.Windows.Forms.Control)) )
                {                    
                    ((System.Windows.Forms.Control)comps[i]).Location = new Point(20*controlSpacingMultiplier, 20*controlSpacingMultiplier);
                    if( controlSpacingMultiplier > 10 )
                        controlSpacingMultiplier = 0;
                    else
                        controlSpacingMultiplier++;
                    parentForm.Controls.Add( (System.Windows.Forms.Control)comps[i] );
                }
            }
        }

        // Displays labels.
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            e.Graphics.DrawString("IToolboxService Control", new Font("Arial", 14), new SolidBrush(Color.Black), 6, 4);
            e.Graphics.DrawString("Category List", new Font("Arial", 8), new SolidBrush(Color.Black), 8, 26);
            e.Graphics.DrawString("Items in Category", new Font("Arial", 8), new SolidBrush(Color.Black), 208, 26);
            e.Graphics.DrawString("(Double-click item to add to parent form)", new Font("Arial", 7), new SolidBrush(Color.Black), 232, 12);
        }  

        private void InitializeComponent()
        {
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.listBox2 = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left);
            this.listBox1.Location = new System.Drawing.Point(8, 41);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(192, 368);
            this.listBox1.TabIndex = 0;
            this.listBox1.SelectedIndexChanged += new System.EventHandler(this.UpdateSelectedCategory);
            this.listBox2.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.listBox2.Location = new System.Drawing.Point(208, 41);
            this.listBox2.Name = "listBox2";
            this.listBox2.Size = new System.Drawing.Size(228, 368);
            this.listBox2.TabIndex = 3;
            this.BackColor = System.Drawing.Color.Beige;
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.listBox2,
                                                                          this.listBox1});
            this.Location = new System.Drawing.Point(500, 400);
            this.Name = "IToolboxServiceControl";
            this.Size = new System.Drawing.Size(442, 422);
            this.ResumeLayout(false);
        }		
    }
    
    // This designer passes window messages to the controls at design time.    
    public class WindowMessageDesigner : System.Windows.Forms.Design.ControlDesigner
    {
        public WindowMessageDesigner()
        {
        }
        
        // Window procedure override passes events to control.
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {   
            if( m.HWnd == this.Control.Handle )
                base.WndProc(ref m);            
            else            
                this.DefWndProc(ref m);            
        }        
    }
}
Imports System.Collections
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing
Imports System.Drawing.Design
Imports System.Data
Imports System.Diagnostics
Imports System.Reflection
Imports System.Windows.Forms

' Provides an example control that functions in design mode to 
' demonstrate use of the IToolboxService to list and select toolbox 
' categories and items, and to add components or controls 
' to the parent form using code.
<DesignerAttribute(GetType(WindowMessageDesigner), GetType(IDesigner))> _
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Public Class IToolboxServiceControl
    Inherits System.Windows.Forms.UserControl

    Private WithEvents listBox1 As System.Windows.Forms.ListBox
    Private listBox2 As System.Windows.Forms.ListBox
    Private toolboxService As IToolboxService = Nothing
    Private tools As ToolboxItemCollection
    Private controlSpacingMultiplier As Integer

    Public Sub New()
        InitializeComponent()
        AddHandler listBox2.DoubleClick, AddressOf Me.CreateComponent
        controlSpacingMultiplier = 0
    End Sub

    ' Obtain or reset IToolboxService reference on each siting of control.
    Public Overrides Property Site() As System.ComponentModel.ISite
        Get
            Return MyBase.Site
        End Get
        Set(ByVal Value As System.ComponentModel.ISite)
            MyBase.Site = Value

            ' If the component was sited, attempt to obtain 
            ' an IToolboxService instance.
            If (MyBase.Site IsNot Nothing) Then
                toolboxService = CType(Me.GetService(GetType(IToolboxService)), IToolboxService)
                ' If an IToolboxService instance was located, update the 
                ' category list.
                If (toolboxService IsNot Nothing) Then
                    UpdateLists()
                End If
            Else
                toolboxService = Nothing
            End If
        End Set
    End Property

    ' Updates the list of categories and the list of items in the 
    ' selected category.
    Private Sub UpdateLists()
        If (toolboxService IsNot Nothing) Then
            RemoveHandler listBox1.SelectedIndexChanged, AddressOf Me.UpdateSelectedCategory
            RemoveHandler listBox2.SelectedIndexChanged, AddressOf Me.UpdateSelectedItem
            listBox1.Items.Clear()
            Dim i As Integer
            For i = 0 To toolboxService.CategoryNames.Count - 1
                listBox1.Items.Add(toolboxService.CategoryNames(i))
                If toolboxService.CategoryNames(i) = toolboxService.SelectedCategory Then
                    listBox1.SelectedIndex = i
                    tools = toolboxService.GetToolboxItems(toolboxService.SelectedCategory)
                    listBox2.Items.Clear()
                    Dim j As Integer
                    For j = 0 To tools.Count - 1
                        listBox2.Items.Add(tools(j).DisplayName)
                    Next j
                End If
            Next i
            AddHandler Me.listBox1.SelectedIndexChanged, AddressOf Me.UpdateSelectedCategory
            AddHandler Me.listBox2.SelectedIndexChanged, AddressOf Me.UpdateSelectedItem
        End If
    End Sub

    ' Sets the selected category when a category is clicked in the 
    ' category list.
    Private Sub UpdateSelectedCategory(ByVal sender As Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
        If (toolboxService IsNot Nothing) Then
            toolboxService.SelectedCategory = CStr(listBox1.SelectedItem)
            UpdateLists()
        End If
    End Sub

    ' Sets the selected item when an item is clicked in the item list.
    Private Sub UpdateSelectedItem(ByVal sender As Object, ByVal e As System.EventArgs)
        If (toolboxService IsNot Nothing) Then
            If listBox1.SelectedIndex <> -1 Then
                If CStr(listBox1.SelectedItem) = toolboxService.SelectedCategory Then
                    toolboxService.SetSelectedToolboxItem(tools(listBox2.SelectedIndex))
                Else
                    UpdateLists()
                End If
            End If
        End If
    End Sub

    ' Creates a control from a double-clicked toolbox item and adds 
    ' it to the parent form.
    Private Sub CreateComponent(ByVal sender As Object, ByVal e As EventArgs)

        ' Obtains an IDesignerHost service from design environment.
        Dim host As IDesignerHost = CType(Me.GetService(GetType(IDesignerHost)), IDesignerHost)

        ' Gets the project components container. (Windows Forms control 
        ' containment depends on controls collections).
        Dim container As IContainer = host.Container

        ' Identifies the parent Form.
        Dim parentForm As System.Windows.Forms.Form = Me.FindForm()

        ' Retrieves the parent Form's designer host.
        Dim parentHost As IDesignerHost = CType(parentForm.Site.GetService(GetType(IDesignerHost)), IDesignerHost)

        ' Create the components.
        Dim comps As IComponent() = Nothing
        Try
            comps = toolboxService.GetSelectedToolboxItem().CreateComponents(parentHost)
        Catch ex As Exception
            ' Catch and show any exceptions to prevent 
            ' disabling the control's UI.
            MessageBox.Show(ex.ToString(), "Exception message")
        End Try

        If comps Is Nothing Then
            Return
        End If

        ' Add any created controls to the parent form's controls 
        ' collection. Note: components are added from the 
        ' ToolboxItem.CreateComponents(IDesignerHost) method.
        Dim i As Integer
        For i = 0 To comps.Length - 1
            If (parentForm IsNot Nothing) AndAlso CType(comps(i), Object).GetType().IsSubclassOf(GetType(System.Windows.Forms.Control)) Then
                CType(comps(i), System.Windows.Forms.Control).Location = New Point(20 * controlSpacingMultiplier, 20 * controlSpacingMultiplier)
                If controlSpacingMultiplier > 10 Then
                    controlSpacingMultiplier = 0
                Else
                    controlSpacingMultiplier += 1
                End If
                parentForm.Controls.Add(CType(comps(i), System.Windows.Forms.Control))
            End If
        Next i
    End Sub

    ' Displays labels.
    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        e.Graphics.DrawString("IToolboxService Control", New Font("Arial", 14), New SolidBrush(Color.Black), 6, 4)
        e.Graphics.DrawString("Category List", New Font("Arial", 8), New SolidBrush(Color.Black), 8, 26)
        e.Graphics.DrawString("Items in Category", New Font("Arial", 8), New SolidBrush(Color.Black), 208, 26)
        e.Graphics.DrawString("(Double-click item to add to parent form)", New Font("Arial", 7), New SolidBrush(Color.Black), 232, 12)
    End Sub

    Private Sub InitializeComponent()
        Me.listBox1 = New System.Windows.Forms.ListBox()
        Me.listBox2 = New System.Windows.Forms.ListBox()
        Me.SuspendLayout()
        Me.listBox1.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left
        Me.listBox1.Location = New System.Drawing.Point(8, 41)
        Me.listBox1.Name = "listBox1"
        Me.listBox1.Size = New System.Drawing.Size(192, 368)
        Me.listBox1.TabIndex = 0
        Me.listBox2.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right
        Me.listBox2.Location = New System.Drawing.Point(208, 41)
        Me.listBox2.Name = "listBox2"
        Me.listBox2.Size = New System.Drawing.Size(228, 368)
        Me.listBox2.TabIndex = 3
        Me.BackColor = System.Drawing.Color.Beige
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.listBox2, Me.listBox1})
        Me.Location = New System.Drawing.Point(500, 400)
        Me.Name = "IToolboxServiceControl"
        Me.Size = New System.Drawing.Size(442, 422)
        Me.ResumeLayout(False)
    End Sub

End Class

' This designer passes window messages to the controls at design time.    
Public Class WindowMessageDesigner
    Inherits System.Windows.Forms.Design.ControlDesigner

    Public Sub New()
    End Sub

    ' Window procedure override passes events to control.
    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.HWnd.Equals(Me.Control.Handle) Then
            MyBase.WndProc(m)
        Else
            Me.DefWndProc(m)
        End If
    End Sub

End Class

В следующем примере кода предоставляется компонент , который использует IToolboxService для добавления обработчика формата данных "Текст" или ToolboxItemCreatorCallbackна панель элементов. Делегат обратного вызова создателя данных передает все текстовые данные, вставленные на панель элементов и перетаскиваемые в форму, в пользовательскую ToolboxItem , создающую TextBox объект , содержащий текст.

#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

Комментарии

Интерфейс IToolboxService предоставляет свойства и методы для добавления и удаления элементов панели элементов и делегатов обратного вызова создателя панели элементов, сериализации и десериализации элементов панели элементов, а также получения сведений о состоянии панели элементов и управления состоянием панели элементов.

Сведения о содержимом панели элементов можно получить с помощью следующих методов:

  • Свойство CategoryNames указывает категории, доступные в данный момент на панели элементов.

  • Свойство SelectedCategory указывает выбранную в данный момент категорию панели элементов.

  • Метод GetToolboxItems извлекает элементы на панели элементов, при необходимости отфильтрованные по указанной категории панели элементов.

  • Метод GetSelectedToolboxItem извлекает выбранный ToolboxItemв данный момент объект .

  • Метод SetSelectedToolboxItem выбирает указанный ToolboxItem в качестве текущего элемента панели элементов.

  • Метод IsSupported указывает, поддерживается ли указанный сериализованный объект , если он является ToolboxItem, указанным узлом конструктора или соответствует ли он указанным атрибутам.

  • Метод IsToolboxItem указывает, является ли указанный сериализованный объект объектом ToolboxItem.

Вы можете добавлять и удалять элементы панели элементов с помощью следующих методов:

  • Метод AddToolboxItem добавляет на ToolboxItem панель элементов, создавая при необходимости указанную категорию, если она не существует.

  • Метод AddLinkedToolboxItem добавляет на ToolboxItem панель элементов , которая включена только для текущего проекта.

  • Метод RemoveToolboxItem удаляет указанный ToolboxItemобъект .

  • Метод AddCreator добавляет делегат, способный ToolboxItemCreatorCallback преобразовать некоторые типы данных, хранящихся на панели элементов, в ToolboxItem.

  • Метод RemoveCreator удаляет все ToolboxItemCreatorCallback делегаты для указанного типа данных.

Вы можете обновить панель элементов, пометить элемент панели элементов как используемый или установить курсор мыши на курсор, представляющий текущий элемент панели элементов, используя следующие методы:

  • Метод Refresh обновляет отображение панели элементов в соответствии с текущим состоянием элементов панели элементов.

  • Метод SelectedToolboxItemUsed сообщает панели элементов о том, что выбранный элемент панели элементов был использован.

  • Метод SetCursor задает курсор мыши, представляющий текущий элемент панели элементов.

Панель элементов можно использовать для сериализации или десериализации элемента панели элементов с помощью следующих методов:

  • Метод DeserializeToolboxItem пытается вернуть ToolboxItem из указанного сериализованного объекта элемента панели элементов.

  • Метод SerializeToolboxItem возвращает сериализованный объект , представляющий указанный ToolboxItemобъект .

Свойства

CategoryNames

Получает имена всех категорий средств имеющихся в данный момент на панели инструментов.

SelectedCategory

Получает или задает имя выбранной в данный момент категории средств с панели инструментов.

Методы

AddCreator(ToolboxItemCreatorCallback, String)

Добавляет создатель нового элемента панели инструментов для заданного формата данных.

AddCreator(ToolboxItemCreatorCallback, String, IDesignerHost)

Добавляет создатель нового элемента панели инструментов для заданных формата данных и хост-узла конструктора.

AddLinkedToolboxItem(ToolboxItem, IDesignerHost)

Добавляет заданный связанный с проектом элемент на панель инструментов.

AddLinkedToolboxItem(ToolboxItem, String, IDesignerHost)

Добавляет на панель инструментов заданный связанный с проектом элемент определенной категории.

AddToolboxItem(ToolboxItem)

Добавляет заданный элемент панели инструментов на панель инструментов.

AddToolboxItem(ToolboxItem, String)

Добавляет указанный элемент заданной категории на панель инструментов.

DeserializeToolboxItem(Object)

Получает элемент панели инструментов из указанного объекта, который представляет элемент панели в сериализованной форме.

DeserializeToolboxItem(Object, IDesignerHost)

Получает элемент панели инструментов из указанного объекта, который представляет элемент панели в сериализованной форме, с помощью указанного узла конструктора.

GetSelectedToolboxItem()

Получает выбранный в данный момент элемент панели инструментов.

GetSelectedToolboxItem(IDesignerHost)

Получает выбранный в данный момент элемент панели инструментов, если это доступно для всех конструкторов или поддерживает определенный конструктор.

GetToolboxItems()

Получает полную коллекцию элементов панели инструментов из панели инструментов.

GetToolboxItems(IDesignerHost)

Получает коллекцию элементов панели элементов, связанных с указанным узлом конструктора из панели элементов.

GetToolboxItems(String)

Получает из панели инструментов коллекцию элементов определенной категории.

GetToolboxItems(String, IDesignerHost)

Получает из панели инструментов коллекцию элементов панели инструментов, которые сопоставлены указанным хост-узлу конструктора и категории.

IsSupported(Object, ICollection)

Получает значение, определяющее, соответствует ли указанный объект, который представляет сериализованный элемент панели инструментов, заданным атрибутам.

IsSupported(Object, IDesignerHost)

Получает значение, определяющее, может ли указанный объект, который представляет сериализованный элемент панели инструментов, быть использован указанным хост-узелом конструктора.

IsToolboxItem(Object)

Получает значение, указывающее, является ли указанный объект сериализованным элементом панели инструментов.

IsToolboxItem(Object, IDesignerHost)

Получает значение, указывающее, является ли заданный объект сериализованным элементом панели инструментов, используя указанный хост-узел конструктора.

Refresh()

Обновляет состояние элементов панели инструментов.

RemoveCreator(String)

Удаляет ранее добавленный разработчик элемента панели инструментов для форматирования указанных данных.

RemoveCreator(String, IDesignerHost)

Удаляет ранее добавленный разработчик, который связан с указанным форматированием данных и определенным узелом конструктора.

RemoveToolboxItem(ToolboxItem)

Удаляет заданный элемент панели инструментов из панели инструментов.

RemoveToolboxItem(ToolboxItem, String)

Удаляет заданный элемент панели инструментов из панели инструментов.

SelectedToolboxItemUsed()

Уведомляет службу панели инструментов, что выбранное средство было использовано.

SerializeToolboxItem(ToolboxItem)

Получает сериализованный объект, который представляет выбранный элемент панели инструментов.

SetCursor()

Устанавливает для курсора текущего приложения курсор, представляющий текущее выбранное средство.

SetSelectedToolboxItem(ToolboxItem)

Выбирает указанный элемент панели инструментов.

Применяется к