Exportieren (0) Drucken
Alle erweitern

IToolboxService-Schnittstelle

Stellt Methoden und Eigenschaften zum Verwalten und Abfragen der Toolbox in der Entwicklungsumgebung bereit.

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

[GuidAttribute("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76")] 
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] 
public interface IToolboxService
/** @attribute GuidAttribute("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76") */ 
/** @attribute InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) */ 
public interface IToolboxService
GuidAttribute("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76") 
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) 
public interface IToolboxService

Die IToolboxService-Schnittstelle stellt Eigenschaften und Methoden zum Hinzufügen und Entfernen von Toolboxelementen und Rückrufdelegaten für die Toolboxerstellung, zum Serialisieren und Deserialisieren von Toolboxelementen, zum Abrufen von Informationen zum Toolboxzustand und zum Verwalten des Toolboxzustands bereit.

Sie können Informationen über den Inhalt der Toolbox mit den folgenden Methoden abrufen:

  • Die CategoryNames-Eigenschaft gibt die derzeit in der Toolbox verfügbaren Kategorien an.

  • Die SelectedCategory-Eigenschaft gibt die derzeit ausgewählte Toolboxkategorie an.

  • Die GetToolboxItems-Methode ruft die Elemente aus der Toolbox ab, die optional durch eine angegebene Toolboxkategorie gefiltert werden.

  • Die GetSelectedToolboxItem-Methode ruft das derzeit ausgewählte ToolboxItem ab.

  • Die SetSelectedToolboxItem-Methode wählt das angegebene ToolboxItem als aktuelles Toolboxelement aus.

  • Die IsSupported-Methode gibt an, ob das angegebene serialisierte Objekt vom angegebenen Designerhost unterstützt wird oder ob es den angegebenen Attributen entspricht, wenn es sich dabei um ein ToolboxItem handelt.

  • Die IsToolboxItem-Methode gibt an, ob das angegebene serialisierte Objekt ein ToolboxItem ist.

Sie können Toolboxelemente mit den folgenden Methoden hinzufügen und entfernen:

  • Die AddToolboxItem-Methode fügt der Toolbox ein ToolboxItem hinzu und erstellt die optional angegebene Kategorie, sofern sie nicht vorhanden ist.

  • Die AddLinkedToolboxItem-Methode fügt ein ToolboxItem hinzu, das für die Toolbox ausschließlich für das aktuelle Projekt aktiviert ist.

  • Die RemoveToolboxItem-Methode entfernt das angegebene ToolboxItem.

  • Die AddCreator-Methode fügt einen ToolboxItemCreatorCallback-Delegaten hinzu, der in der Toolbox gespeicherte Daten eines bestimmten Typs in ein ToolboxItem konvertieren kann.

  • Die RemoveCreator-Methode entfernt alle ToolboxItemCreatorCallback-Delegaten für den angegebenen Datentyp.

Mithilfe der folgenden Methoden können Sie die Toolbox aktualisieren, ein Toolboxelement als verwendet markieren oder den Mauszeiger auf einen Cursor festlegen, der das aktuelle Toolboxelement darstellt:

  • Die Refresh-Methode aktualisiert die Toolboxanzeige, um den aktuellen Zustand der Toolboxelemente wiederzugeben.

  • Die SelectedToolboxItemUsed-Methode signalisiert der Toolbox, dass das ausgewählte Toolboxelement verwendet wurde.

  • Die SetCursor-Methode legt den Mauszeiger auf einen Cursor fest, der das aktuelle Toolboxelement darstellt.

Mithilfe der Toolbox können Sie ein Toolboxelement unter Verwendung der folgenden Methoden serialisieren oder deserialisieren:

  • Die DeserializeToolboxItem-Methode versucht, ein ToolboxItem aus dem angegebenen serialisierten Toolboxelementobjekt zurückzugeben.

  • Die SerializeToolboxItem-Methode gibt ein serialisiertes Objekt zurück, das das angegebene ToolboxItem darstellt.

Im folgenden Codebeispiel wird die Verwendung des IToolboxService im Entwurfsmodus zum Auflisten und Auswählen von Toolboxkategorien und -elementen, zum Erstellen von Komponenten oder Steuerelementen aus Toolboxelementen und zum Hinzufügen dieser Komponenten und Steuerelemente zu einem Form veranschaulicht. Um dieses Beispiel zu verwenden, kompilieren Sie den Code in eine Assembly, und fügen Sie in einer Windows Forms-Anwendung einen Verweis auf die Assembly hinzu. Wenn Sie Visual Studio verwenden, wird das IToolboxServiceControl automatisch der Toolbox hinzugefügt. Erstellen Sie eine Instanz des IToolboxServiceControl in einem Formular, um dessen Verhalten zu testen.

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))]
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] 
    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.
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] 
        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);            
        }        
    }
}

package IToolboxServiceExample;

import System.*;
import System.Collections.*;
import System.ComponentModel.*;
import System.ComponentModel.Design.*;
import System.Drawing.*;
import System.Drawing.Design.*;
import System.Data.*;
import System.Diagnostics.*;
import System.Windows.Forms.*;
import System.Security.Permissions.*;

// 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.

/** @attribute DesignerAttribute(WindowMessageDesigner.class,
    IDesigner.class)
 */
public class IToolboxServiceControl extends 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.add_DoubleClick(new EventHandler(this.CreateComponent));
        controlSpacingMultiplier = 0;
    } //IToolboxServiceControl()

    // Obtain or reset IToolboxService reference on each siting of control.
    /** @property
     */
    public System.ComponentModel.ISite get_Site()
    {
        return super.get_Site();
    } // get_Site

    /** @property 
     */
    public void set_Site(System.ComponentModel.ISite value)
    {
        super.set_Site(value);

        // If the component was sited, attempt to obtain 
        // an IToolboxService instance.
        if (super.get_Site() != null) {
            toolboxService = (IToolboxService)this.GetService(
                IToolboxService.class.ToType());

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

    // Updates the list of categories and the list of items in the
    //selected category.
    /** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
    */
    private void UpdateLists()
    {
        if (toolboxService != null) {
            this.listBox1.remove_SelectedIndexChanged(new System.EventHandler(
                this.UpdateSelectedCategory));
            this.listBox2.remove_SelectedIndexChanged(new System.EventHandler(
                this.UpdateSelectedItem));
            listBox1.get_Items().Clear();
            for (int i = 0; i < toolboxService.get_CategoryNames().
                    get_Count(); i++) {
                listBox1.get_Items().Add(toolboxService.get_CategoryNames().
                    get_Item(i));
                if (toolboxService.get_CategoryNames().get_Item(i).Equals(
                    toolboxService.get_SelectedCategory())) {
                    listBox1.set_SelectedIndex(i);
                    tools = toolboxService.GetToolboxItems(toolboxService.
                        get_SelectedCategory());
                    listBox2.get_Items().Clear();
                    for (int j = 0; j < tools.get_Count(); j++) {
                        listBox2.get_Items().Add(tools.get_Item(j).
                            get_DisplayName());
                    }
                }
            }
            this.listBox1.add_SelectedIndexChanged(new System.EventHandler(
                this.UpdateSelectedCategory));
            this.listBox2.add_SelectedIndexChanged(new System.EventHandler(
                this.UpdateSelectedItem));
        }
    } //UpdateLists

    // 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.set_SelectedCategory(listBox1.get_SelectedItems().
                ToString());
            UpdateLists();
        }
    } //UpdateSelectedCategory

    // 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.get_SelectedIndex() != -1) {
                if ((listBox1.get_SelectedItem().ToString()).Equals(
                    toolboxService.get_SelectedCategory())) {
                    toolboxService.SetSelectedToolboxItem(tools.get_Item(
                        listBox2.get_SelectedIndex()));
                }
                else {
                    UpdateLists();
                }
            }
        }
    } //UpdateSelectedItem

    // 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(
            IDesignerHost.class.ToType());

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

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

        // Retrieves the parent Form's designer host.
        IDesignerHost parentHost = (IDesignerHost)parentForm.get_Site().
            GetService(IDesignerHost.class.ToType());

        // Create the components.
        IComponent comps[] = null;

        try {
            comps = toolboxService.GetSelectedToolboxItem().
                CreateComponents(parentHost);
        }
        catch (System.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(
                    System.Windows.Forms.Control.class.ToType()))) {
                ((System.Windows.Forms.Control)comps[i]).set_Location(
                    new Point(20 * controlSpacingMultiplier, 20 
                    * controlSpacingMultiplier));

                if (controlSpacingMultiplier > 10) {
                    controlSpacingMultiplier = 0;
                }
                else {
                    controlSpacingMultiplier++;
                }
                parentForm.get_Controls().Add((System.Windows.Forms.
                    Control)comps[i]);
            }
        }
    } //CreateComponent

    // Displays labels.
    protected void OnPaint(System.Windows.Forms.PaintEventArgs e)
    {
        e.get_Graphics().DrawString("IToolboxService Control", new Font(
            "Arial", 14), new SolidBrush(Color.get_Black()), 6, 4);

        e.get_Graphics().DrawString("Category List", new Font("Arial", 8),
            new SolidBrush(Color.get_Black()), 8, 26);

        e.get_Graphics().DrawString("Items in Category", new Font("Arial", 8),
            new SolidBrush(Color.get_Black()), 208, 26);
        e.get_Graphics().DrawString("(Double-click item to add to parent form)",
            new Font("Arial", 7), new SolidBrush(Color.get_Black()), 232, 12);
    } //OnPaint

    private void InitializeComponent()
    {
        this.listBox1 = new System.Windows.Forms.ListBox();
        this.listBox2 = new System.Windows.Forms.ListBox();
        this.SuspendLayout();
        this.listBox1.set_Anchor(System.Windows.Forms.AnchorStyles.Top 
            | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.
            AnchorStyles.Left);
        this.listBox1.set_Location(new System.Drawing.Point(8, 41));
        this.listBox1.set_Name("listBox1");
        this.listBox1.set_Size(new System.Drawing.Size(192, 368));
        this.listBox1.set_TabIndex(0);
        this.listBox1.add_SelectedIndexChanged(new System.EventHandler(this.
            UpdateSelectedCategory));
        this.listBox2.set_Anchor(System.Windows.Forms.AnchorStyles.Top 
            | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.
            Forms.AnchorStyles. Left | System.Windows.Forms.AnchorStyles.
            Right);
        this.listBox2.set_Location(new System.Drawing.Point(208, 41));
        this.listBox2.set_Name("listBox2");
        this.listBox2.set_Size(new System.Drawing.Size(228, 368));
        this.listBox2.set_TabIndex(3);
        this.set_BackColor(System.Drawing.Color.get_Beige());
        this.get_Controls().AddRange(new System.Windows.Forms.Control[] {this.
            listBox2, this.listBox1});
        this.set_Location(new System.Drawing.Point(500, 400));
        this.set_Name("IToolboxServiceControl");
        this.set_Size(new System.Drawing.Size(442, 422));
        this.ResumeLayout(false);
    } //InitializeComponent
} //IToolboxServiceControl

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

    // Window procedure override passes events to control.
    /** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
    */
    protected void WndProc(System.Windows.Forms.Message m)
    {
        if (m.get_HWnd().Equals(this.get_Control().get_Handle())) {
            super.WndProc(m);
        }
        else {
            this.DefWndProc(m);
        }
    } //WndProc
} //WindowMessageDesigner

Im folgenden Codebeispiel wird eine Komponente bereitgestellt, die mit IToolboxService der Toolbox einen Text-Datenformathandler oder ToolboxItemCreatorCallback hinzufügt. Der Datenersteller-Rückrufdelegat übergibt alle an die Toolbox übergebenen und in ein Formular gezogenen Textdaten an ein benutzerdefiniertes ToolboxItem, das eine TextBox mit dem Text erstellt.

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

namespace TextDataTextBoxComponent
{
    // Component that adds a "Text" data format ToolboxItemCreatorCallback 
    // to the Toolbox that creates a custom ToolboxItem that 
    // creates a TextBox containing the text data.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    public class TextDataTextBoxComponent : System.ComponentModel.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)
        {
            string[] formats = ((System.Windows.Forms.DataObject)serializedObject).GetFormats();
            if( ((System.Windows.Forms.DataObject)serializedObject).GetDataPresent("System.String", true) )           
                return new TextToolboxItem( (string)((System.Windows.Forms.DataObject)serializedObject).GetData("System.String", true) );            
            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.
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] 
    public class TextToolboxItem : System.Drawing.Design.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.
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] 
        protected override System.ComponentModel.IComponent[] CreateComponentsCore(System.ComponentModel.Design.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;
        }
    }
}

package TextDataTextBoxComponent;

import System.*;
import System.ComponentModel.*;
import System.ComponentModel.Design.*;
import System.Drawing.*;
import System.Drawing.Design.*;
import System.Windows.Forms.*;
// Component that adds a "Text" data format ToolboxItemCreatorCallback 
// to the Toolbox that creates a custom ToolboxItem that 
// creates a TextBox containing the text data.
public class TextDataTextBoxComponent extends System.ComponentModel.Component
{
    private boolean creatorAdded = false;
    private IToolboxService ts;

    public TextDataTextBoxComponent()
    {
    } //TextDataTextBoxComponent

    // ISite override to register TextBox creator
    /** @property 
     */
    public System.ComponentModel.ISite get_Site()
    {
        return super.get_Site();
    } //get_Site

    /** @property 
     */
    public void set_Site(System.ComponentModel.ISite value)
    {
        if (value != null) {
            super.set_Site(value);
            if (!(creatorAdded)) {
                AddTextTextBoxCreator();
            }
        }
        else {
            if (creatorAdded) {
                RemoveTextTextBoxCreator();
            }
            super.set_Site(value);
        }
    } //set_Site

    // 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(IToolboxService.class.ToType());
        if (ts != null) {
            ToolboxItemCreatorCallback textCreator =
                new ToolboxItemCreatorCallback(this.CreateTextBoxForText);
            try {
                ts.AddCreator(textCreator, "Text",
                    (IDesignerHost)GetService(IDesignerHost.class.ToType()));
                creatorAdded = true;
            }
            catch (System.Exception ex) {
                MessageBox.Show(ex.ToString(), "Exception Information");
            }
        }
    } //AddTextTextBoxCreator

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

    // ToolboxItemCreatorCallback delegate format method to create 
    // the toolbox item.
    private ToolboxItem CreateTextBoxForText(Object serializedObject,
        String format)
    {
        String formats[] = 
            ((System.Windows.Forms.DataObject)serializedObject).GetFormats();
        if (((System.Windows.Forms.DataObject)serializedObject).
            GetDataPresent("System.String", true)) {
            return new TextToolboxItem((String)
                (((System.Windows.Forms.DataObject)serializedObject).
                GetData("System.String", true)));
        }
        return null;
    } //CreateTextBoxForText

    protected void Dispose(boolean disposing)
    {
        if (creatorAdded) {
            RemoveTextTextBoxCreator();
        }
    } //Dispose
} //TextDataTextBoxComponent

// Custom toolbox item creates a TextBox and sets its Text property
// to the constructor-specified text.
public class TextToolboxItem extends System.Drawing.Design.ToolboxItem
{
    private String text;

    /** @delegate 
     */
    private delegate void SetTextMethodHandler(Control c, String text);

    /** @attribute System.Security.Permissions.PermissionSet(
        System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")
     */
    public TextToolboxItem(String text)
    {
        this.text = text;
    } //TextToolboxItem

    // ToolboxItem.CreateComponentsCore override to create the TextBox 
    // and link a method to set its Text property.
    /** @attribute System.Security.Permissions.PermissionSet(
        System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")
     */
    protected System.ComponentModel.IComponent[] CreateComponentsCore(
        System.ComponentModel.Design.IDesignerHost host)
    {
        System.Windows.Forms.TextBox textbox =
            (TextBox)host.CreateComponent(TextBox.class.ToType());
        // 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 = (Control)host.get_RootComponent();
        c.BeginInvoke(new SetTextMethodHandler(OnSetText),
            new Object[] { textbox, text });

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

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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0
Anzeigen:
© 2015 Microsoft