ToolboxItemCreatorCallback Delegado

Definición

Proporciona un mecanismo de devolución de llamada que puede crear un ToolboxItem.

public delegate System::Drawing::Design::ToolboxItem ^ ToolboxItemCreatorCallback(System::Object ^ serializedObject, System::String ^ format);
public delegate System.Drawing.Design.ToolboxItem ToolboxItemCreatorCallback(object serializedObject, string format);
type ToolboxItemCreatorCallback = delegate of obj * string -> ToolboxItem
Public Delegate Function ToolboxItemCreatorCallback(serializedObject As Object, format As String) As ToolboxItem 

Parámetros

serializedObject
Object

Objeto que contiene los datos para los que se va a crear un ToolboxItem.

format
String

Nombre del formato de datos de Portapapeles para el que se va a crear un objeto ToolboxItem.

Valor devuelto

Objeto ToolboxItem deserializado especificado por serializedObject.

Ejemplos

En el ejemplo siguiente se proporciona un componente que usa IToolboxService para agregar un controlador de formato de datos "Text" o ToolboxItemCreatorCallback, al cuadro de herramientas. El delegado de devolución de llamada del creador de datos pasa los datos de texto pegados al cuadro de herramientas y arrastrados a un formulario a un personalizado ToolboxItem que crea un TextBox objeto que contiene el texto.

#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

Comentarios

Puede implementar un método creador de elementos de cuadro de herramientas con una firma de método que coincida con la firma del método de este tipo delegado que crea un elemento de cuadro de herramientas a partir de cualquier objeto de un formato de datos del Portapapeles determinado colocado en el cuadro de herramientas. Por ejemplo, puede diseñar un creador de elementos de cuadro de herramientas que cree un TextBox para almacenar el texto pegado en el cuadro de herramientas desde el Portapapeles. Puede usar el AddCreator método de IToolboxService para agregar un ToolboxItemCreatorCallback controlador de eventos para un tipo de datos determinado al cuadro de herramientas. El serializedObject parámetro contiene el objeto de datos.

Cuando se crea un delegado ToolboxItemCreatorCallback, se identifica el método que controlará el evento. Para asociar el evento al controlador, se debe agregar una instancia del delegado al evento. Siempre que se produce el evento, se llama a su controlador, a menos que se quite el delegado. Para obtener más información sobre los delegados del controlador de eventos, vea Control y generación de eventos.

Métodos de extensión

GetMethodInfo(Delegate)

Obtiene un objeto que representa el método representado por el delegado especificado.

Se aplica a