Leggi in inglese

Condividi tramite


IToolboxService Interfaccia

Definizione

Fornisce metodi e proprietà per gestire ed eseguire query sulla casella degli strumenti nell'ambiente di sviluppo.

C#
[System.Runtime.InteropServices.Guid("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76")]
[System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IToolboxService
Derivato
Attributi

Esempio

Nell'esempio di codice seguente viene illustrato l'uso IToolboxService della modalità di progettazione per elencare e selezionare categorie e elementi della casella degli strumenti e per creare componenti o controlli dagli elementi della casella degli strumenti e aggiungerli a un Formoggetto . Per usare l'esempio, compilare il codice in un assembly e aggiungere un riferimento all'assembly in un'applicazione Windows Forms. Se si usa Visual Studio, l'oggetto IToolboxServiceControl viene aggiunto automaticamente alla casella degli strumenti. Create un'istanza di in IToolboxServiceControl un modulo per testare il comportamento.

C#
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);            
        }        
    }
}

Nell'esempio IToolboxService di codice seguente viene fornito un componente che usa per aggiungere un gestore del formato dati "Text" o ToolboxItemCreatorCallback, alla casella degli strumenti. Il delegato di callback dell'autore dei dati passa tutti i dati di testo incollati alla casella degli strumenti e trascinati in un modulo a un oggetto personalizzato ToolboxItem che crea un TextBox oggetto contenente il testo.

C#
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;
        }
    }
}

Commenti

L'interfaccia IToolboxService fornisce proprietà e metodi per aggiungere e rimuovere gli elementi della casella degli strumenti e i delegati di callback dell'autore della casella degli strumenti, la serializzazione e la deserializzazione degli elementi della casella degli strumenti e il recupero delle informazioni sullo stato della casella degli strumenti e la gestione dello stato della casella degli strumenti.

È possibile recuperare informazioni sul contenuto della casella degli strumenti con i metodi seguenti:

  • La CategoryNames proprietà indica le categorie attualmente disponibili nella casella degli strumenti.

  • La SelectedCategory proprietà indica la categoria della casella degli strumenti attualmente selezionata.

  • Il GetToolboxItems metodo recupera gli elementi della casella degli strumenti, facoltativamente filtrati da una categoria specificata della casella degli strumenti.

  • Il GetSelectedToolboxItem metodo recupera l'oggetto attualmente selezionato ToolboxItem.

  • Il SetSelectedToolboxItem metodo seleziona l'oggetto specificato ToolboxItem come elemento della casella degli strumenti corrente.

  • Il IsSupported metodo indica se l'oggetto serializzato specificato, se è un ToolboxItemoggetto , è supportato dall'host della finestra di progettazione specificato o se corrisponde agli attributi specificati.

  • Il IsToolboxItem metodo indica se l'oggetto serializzato specificato è un ToolboxItemoggetto .

È possibile aggiungere e rimuovere gli elementi della casella degli strumenti con i metodi seguenti:

È possibile aggiornare la casella degli strumenti, contrassegnare un elemento della casella degli strumenti come usato o impostare il cursore del mouse su un cursore che rappresenta l'elemento corrente della casella degli strumenti usando i metodi seguenti:

  • Il Refresh metodo aggiorna la visualizzazione della casella degli strumenti per riflettere lo stato corrente degli elementi della casella degli strumenti.

  • Il SelectedToolboxItemUsed metodo segnala che l'elemento della casella degli strumenti selezionato è stato usato.

  • Il SetCursor metodo imposta il cursore del mouse su un cursore che rappresenta l'elemento corrente della casella degli strumenti.

È possibile usare la casella degli strumenti per serializzare o deserializzare un elemento della casella degli strumenti usando i metodi seguenti:

Proprietà

CategoryNames

Recupera i nomi di tutte le categorie degli strumenti presenti correntemente nella casella degli strumenti.

SelectedCategory

Recupera o imposta il nome della categoria degli strumenti correntemente selezionata nella casella degli strumenti.

Metodi

AddCreator(ToolboxItemCreatorCallback, String)

Aggiunge un nuovo creatore di elementi della casella degli strumenti per un formato di dati specificato.

AddCreator(ToolboxItemCreatorCallback, String, IDesignerHost)

Aggiunge un nuovo creatore di elementi della casella degli strumenti per un formato di dati specificato e un host di progettazione.

AddLinkedToolboxItem(ToolboxItem, IDesignerHost)

Aggiunge alla casella degli strumenti un elemento collegato al progetto specificato.

AddLinkedToolboxItem(ToolboxItem, String, IDesignerHost)

Aggiunge l'elemento della casella degli strumenti collegato al progetto specificato nella categoria indicata.

AddToolboxItem(ToolboxItem)

Aggiunge l'elemento specificato alla casella degli strumenti.

AddToolboxItem(ToolboxItem, String)

Aggiunge alla casella degli strumenti l'elemento specificato nella categoria indicata.

DeserializeToolboxItem(Object)

Ottiene un elemento della casella degli strumenti dall’oggetto specificato che rappresenta un elemento della casella degli strumenti in un form serializzato.

DeserializeToolboxItem(Object, IDesignerHost)

Recupera un elemento della casella degli strumenti dall’oggetto specificato che rappresenta un elemento della casella degli strumenti in un form serializzato, utilizzando l’host di progettazione specificato.

GetSelectedToolboxItem()

Ottiene l'elemento della casella degli strumenti correntemente selezionato.

GetSelectedToolboxItem(IDesignerHost)

Ottiene l’elemento della casella degli strumenti correntemente selezionato se disponibile in tutte le finestre di progettazione o se supporta la finestra di progettazione specificata.

GetToolboxItems()

Ottiene l’insieme completo di elementi dalla casella degli strumenti.

GetToolboxItems(IDesignerHost)

Ottiene dalla casella degli strumenti l’insieme degli elementi associati all’host di progettazione specificato.

GetToolboxItems(String)

Ottiene dalla casella degli strumenti un insieme di elementi corrispondenti alla categoria specificata.

GetToolboxItems(String, IDesignerHost)

Ottiene dalla casella degli strumenti l’insieme degli elementi associati all’host di progettazione e alla categoria specificati.

IsSupported(Object, ICollection)

Ottiene un valore che indica se l’oggetto specificato che rappresenta un elemento serializzato della casella degli strumenti corrisponde agli attributi specificati.

IsSupported(Object, IDesignerHost)

Ottiene un valore che indica se l’oggetto specificato che rappresenta un elemento serializzato della casella degli strumenti può essere utilizzato dall’host di progettazione specificato.

IsToolboxItem(Object)

Ottiene un valore che indica se l'oggetto specificato è un elemento serializzato della casella degli strumenti.

IsToolboxItem(Object, IDesignerHost)

Ottiene un valore che indica se l'oggetto specificato è un elemento serializzato della casella degli strumenti, utilizzando l’host di progettazione specificato.

Refresh()

Aggiorna lo stato degli elementi della casella degli strumenti.

RemoveCreator(String)

Rimuove un creatore di elementi della casella degli strumenti aggiunto in precedenza, del formato dati specificato.

RemoveCreator(String, IDesignerHost)

Rimuove un creatore della casella degli strumenti aggiunto in precedenza associato al formato di dati specificato e all’host di progettazione indicato.

RemoveToolboxItem(ToolboxItem)

Rimuove dalla casella degli strumenti l'elemento della casella degli strumenti specificato.

RemoveToolboxItem(ToolboxItem, String)

Rimuove dalla casella degli strumenti l'elemento della casella degli strumenti specificato.

SelectedToolboxItemUsed()

Notifica al servizio della casella degli strumenti che lo strumento selezionato è stato utilizzato.

SerializeToolboxItem(ToolboxItem)

Ottiene un oggetto serializzabile che rappresenta l'elemento della casella degli strumenti specificato.

SetCursor()

Imposta il cursore dell'applicazione corrente per rappresentare lo strumento correntemente selezionato.

SetSelectedToolboxItem(ToolboxItem)

Seleziona l'elemento della casella degli strumenti specificato.

Si applica a

Prodotto Versioni
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9