使用英语阅读

通过


IToolboxService 接口

定义

提供在开发环境下管理和查询工具箱的方法和属性。

[System.Runtime.InteropServices.Guid("4BACD258-DE64-4048-BC4E-FEDBEF9ACB76")]
[System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IToolboxService
派生
属性

示例

下面的代码示例演示如何在设计模式下使用 IToolboxService 列出和选择工具箱类别和项,以及从工具箱项创建组件或控件并将其添加到 Form。 若要使用示例,请将代码编译为程序集,并在Windows 窗体应用程序中添加对程序集的引用。 如果使用的是 Visual Studio,则 IToolboxServiceControl 会自动添加到 工具箱中。 Create窗体上的 实例IToolboxServiceControl以测试其行为。

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

下面的代码示例提供了一个组件,该组件使用 IToolboxService 向工具箱添加“文本”数据格式处理程序或 ToolboxItemCreatorCallback。 数据创建者回调委托将粘贴到工具箱中并拖动到窗体上的任何文本数据传递给创建TextBox包含文本的自定义ToolboxItem

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

注解

接口 IToolboxService 提供用于添加和删除工具箱项和工具箱创建者回调委托、序列化和反序列化工具箱项以及检索工具箱状态信息以及管理工具箱状态的属性和方法。

可以使用以下方法检索有关工具箱内容的信息:

可以使用以下方法添加和删除工具箱项:

可使用以下方法刷新工具箱、将工具箱项标记为已用,或将鼠标光标设置为表示当前工具箱项的游标:

  • 方法 Refresh 刷新工具箱显示以反映工具箱项的当前状态。

  • 方法 SelectedToolboxItemUsed 向工具箱发出已使用所选工具箱项的信号。

  • 方法 SetCursor 将鼠标光标设置为表示当前工具箱项的游标。

可以使用工具箱使用以下方法序列化或反序列化工具箱项:

属性

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)

选择指定的工具箱项。

适用于

产品 版本
.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