共用方式為


逐步解說: 自訂動態 ToolboxItem 組態

這個逐步解說會示範如何受管理的 VSPackage 可以提供動態組態支援ToolboxItem物件。

注意事項注意事項

若要將自訂控制項加入至 [工具箱] 中最簡單的方法是使用工具箱控制項樣板以 Visual Studio 的 10 SDK 隨附。本主題和進階的工具箱開發有關。

如需有關如何使用範本建立工具箱控制項的詳細資訊,請參閱How to: 建立使用 Windows Form 的工具箱控制項How to: 建立使用 WPF 的工具箱控制項

本逐步解說會引導您完成下列步驟:

  1. 新增並正確地登錄所有工具箱 VSPackage 物件,藉由使用中的控制項ToolboxItemAttributeToolboxBitmapAttribute類別。

  2. 建立下列兩個控制項,並新增圖示,對每一個都以工具箱

    • 一個控制項宣告相關的預設ToolboxItem

    • 一個控制項宣告相關聯的自訂工具箱項目是衍生自ToolboxItem類別。

  3. 撰寫的實作IConfigureToolboxItem,並註冊藉由執行下列動作:

    1. 定義篩選器類別衍生自IConfigureToolboxItem類別,並指定ToolboxItem做這項實作的執行個體。

    2. 套用ProvideToolboxItemConfigurationAttribute,它會參考篩選的類別,以實作的類別Package VSPackage 的類別。

  4. 註冊的提供者的 VSPackage ToolboxItem物件套用ProvideToolboxItemsAttribute實作的類別來Package VSPackage 的類別。

  5. 在封裝載入時間,使用反映來產生一份所有ToolboxItem VSPackage 所提供的物件。

  6. 建立處理常式的ToolboxInitializedToolboxUpgraded事件。 這樣可以保證,VSPackage ToolboxItem物件就會正確地載入。

  7. 實作命令上強迫重新初始化 VSPackage 工具箱

必要條件

若要完成這個逐步解說中,您必須安裝Visual Studio 2010 SDK。

注意事項注意事項

如需有關 Visual Studio 的 SDK 的詳細資訊,請參閱擴充 Visual Studio 的概觀。若要了解如何下載 Visual Studio 的 SDK,請參閱Visual Studio 擴充性開發人員中心 MSDN 網站上。

Visual Studio 的封裝專案範本的位置

Visual Studio 的封裝的專案範本,請參閱以下三個不同的位置,在新的專案對話方塊:

  1. 在 [Visual Basic 擴充性。 專案的預設語言是 Visual Basic。

  2. 在 [C# 擴充性。 專案的預設語言是 C#。

  3. 在 [其他專案的型別擴充性。 專案的預設語言是 c + +。

建立受管理的 VSPackage

完成下列程序來建立受管理的 VSPackage。

若要建立受管理的 VSPackage 提供工具箱項目

  1. 建立名為 VSPackage ItemConfiguration。 如需詳細資訊,請參閱 逐步解說: 使用 Visual Studio 的封裝範本建立功能表命令

  2. Visual Studio 套件範本中,加入功能表命令。

    命名命令初始化 ItemConfigurationVB 的 Visual Basic 或初始化 ItemConfigurationCS 的視覺 C#。

  3. 對於Visual Basic,將下列命名空間加入至產生的專案中匯入的命名空間清單:

    • Company.ItemConfiguration

    • System

    • System.ComponentModel

    • System.Drawing

    • System.Windows.Forms

  4. 將參考加入至System.Drawing.Design 。NET Framework 的元件。

如果您遵循本逐步解說中一個以上的語言,您必須更新的專案,可以清楚識別自動產生的組件。

若要釐清 Visual Basic 和視覺化 C# VSPackages

  1. For Visual Basic:

    1. 開啟專案屬性,然後選取應用程式 ] 索引標籤。

      將組件名稱變更成 ItemConfigurationVB,並將變更的預設命名空間 Company.ItemConfigurationVB。

    2. 選取 參考 索引標籤。

      更新匯入的命名空間清單。

      移除 Company.ItemConfiguration。

      新增 Company.ItemConfigurationVB。

  2. For Visual C#:

    1. 開啟專案屬性,然後選取應用程式 ] 索引標籤。

      將組件名稱變更成 ItemConfigurationCS,並將變更的預設命名空間 Company.ItemConfigurationCS。

    2. 在程式碼編輯器中開啟 ItemConfigurationPackage 類別。

      若要重新命名現有的命名空間,以滑鼠右鍵按一下現有的命名空間名稱,請使用重整工具ItemConfiguration,指到重構,然後按一下 [ 重新命名。 將名稱變更成 ItemConfigurationCS。

  3. 儲存所有變更。

若要測試產生的程式碼

  1. 編譯並啟動 VSPackage Visual Studio 的實驗登錄區中。

  2. 工具 ] 功能表中,按一下 初始化項目設定 VB初始化項目組態 CS

    如此一來,便會開啟訊息方塊,其中包含表示封裝的功能表項目處理常式所呼叫的文字。

  3. 關閉實驗性質的版本的Visual Studio。

建立工具箱控制項

本章節中,您需要建立並註冊使用者控制項, Control1,來宣告相關的預設工具箱項目。 您也建立並註冊第二個使用者控制項, Control2,與相關聯的自訂工具箱項目, Control2_ToolboxItem,也就是衍生自ToolboxItem類別。 如需有關如何撰寫 Windows Form 控制項,並ToolboxItem類別,請參閱在設計階段開發 Windows Form 控制項

若要建立預設值] 和 [自訂工具箱項目

  1. 使用中的指示, 逐步解說: 自動載入工具箱項目 ,建立預設的工具箱項目] 和 [自訂工具箱項目、,如下所示。

    1. 完成程序中,「 若要建立工具箱將使用預設值 ToolboxItem 的控制。" 更新DescriptionAttribute來參考這個專案。

      產生的程式碼,如Control1類別應該類似下列的程式碼。

      ' Set the display name and custom bitmap to use for this item. 
      ' The build action for the bitmap must be "Embedded Resource".
      <DisplayName("ToolboxMember 1 VB")> _
      <Description("Custom toolbox item from package ItemConfiguration.")> _
      <ToolboxItem(True)> _
      <ToolboxBitmap(GetType(Control1), "Control1.bmp")> _
      Public Class Control1
      
          Public Sub New()
      
              InitializeComponent()
      
              Button1.Text = Me.Name + " Button" 
          End Sub 
      
          Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
              Handles Button1.Click
      
              MessageBox.Show("Hello world from " & Me.ToString())
          End Sub 
      End Class
      
      using System;
      using System.ComponentModel;
      using System.Drawing;
      using System.Windows.Forms;
      
      namespace Company.ItemConfigurationCS
      {
          // Set the display name and custom bitmap to use for this item. 
          // The build action for the bitmap must be "Embedded Resource".
          [DisplayName("ToolboxMember 1 CS")]
          [Description("Custom toolbox item from package ItemConfiguration.")]
          [ToolboxItem(true)]
          [ToolboxBitmap(typeof(Control1), "Control1.bmp")]
          public partial class Control1 : UserControl
          {
              public Control1()
              {
                  InitializeComponent();
      
                  button1.Text = this.Name + " Button";
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  MessageBox.Show("Hello world from " + this.ToString());
              }
          }
      }
      
    2. 完成這個程序中,「 若要建立工具箱使用自訂的 ToolboxItem 衍生類別的控制項。" 更新DescriptionAttribute來參考這個專案。

      產生的程式碼,如Control2和Control2_ToolboxItem類別應該類似下列的程式碼。

      Imports System.Drawing.Design
      Imports System.Globalization
      
      ' Set the display name and custom bitmap to use for Me item. 
      ' The build action for the bitmap must be "Embedded Resource". 
      ' Also declare a custom toolbox item implementation.
      <DisplayName("ToolboxMember 2 VB")> _
      <Description("Custom toolbox item from package ItemConfiguration.")> _
      <ToolboxItem(GetType(Control2_ToolboxItem))> _
      <ToolboxBitmap(GetType(Control2), "Control2.bmp")> _
      Public Class Control2
      
          Public Sub New()
              InitializeComponent()
      
              Button1.Text = Me.Name + " Button" 
          End Sub 
      
          Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
              Handles Button1.Click
      
              MessageBox.Show("Hello world from " & Me.ToString())
          End Sub 
      End Class
      
      <Serializable()> _
      Friend Class Control2_ToolboxItem
          Inherits ToolboxItem
      
          Public Sub New(ByVal toolType As Type)
              MyBase.New(toolType)
          End Sub 
      
          Public Overrides Sub Initialize(ByVal toolType As Type)
      
              If Not toolType.Equals(GetType(Control2)) Then 
                  Throw New ArgumentException( _
                      String.Format(CultureInfo.CurrentCulture, _
                          "The {0} constructor argument must be of type {1}.", _
                          Me.GetType().FullName, GetType(Control2).FullName))
              End If 
      
              MyBase.Initialize(toolType)
          End Sub 
      End Class
      
      using System;
      using System.ComponentModel;
      using System.Drawing;
      using System.Windows.Forms;
      
      using System.Drawing.Design;
      using System.Globalization;
      
      namespace Company.ItemConfigurationCS
      {
          // Set the display name and custom bitmap to use for this item. 
          // The build action for the bitmap must be "Embedded Resource".
          // Also declare a custom toolbox item implementation.
          [DisplayName("ToolboxMember 2 CS")]
          [Description("Custom toolbox item from package ItemConfigurationPackage.")]
          [ToolboxItem(typeof(Control2_ToolboxItem))]
          [ToolboxBitmap(typeof(Control2), "Control2.bmp")]
          public partial class Control2 : UserControl
          {
              public Control2()
              {
                  InitializeComponent();
      
                  button1.Text = this.Name + " Button";
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  MessageBox.Show("Hello world from " + this.ToString());
              }
          }
      
          [Serializable()]
          internal class Control2_ToolboxItem : ToolboxItem
          {
              public Control2_ToolboxItem(Type toolType)
                  : base(toolType) { }
      
              public override void Initialize(Type toolType)
              {
                  if (!toolType.Equals(typeof(Control2)))
                  {
                      throw new ArgumentException(
                          string.Format(CultureInfo.CurrentCulture,
                              "The {0} constructor argument must be of type {1}.",
                              this.GetType().FullName, typeof(Control2).FullName));
                  }
      
                  base.Initialize(toolType);
              }
          }
      }
      
  2. 儲存檔案。

內嵌點陣圖圖示

ToolboxBitmapAttribute會套用至每個控制項的屬性會指定相關於該控制項的哪一個圖示。 建立點陣圖,這兩個控制項,並加以命名,如下所示:

  • Control1.bmp,如Control1類別。

  • Control2.bmp,如Control2類別。

若要將內嵌點陣圖] 圖示的工具箱項目

  1. 新增新的點陣圖到專案中,如下所示:

    1. 方案總管] 中VSPackage 專案上按一下滑鼠右鍵,指向 新增,然後按一下 新的項目

    2. 加入新項目 對話方塊中,選取 點陣圖檔,然後輸入點陣圖的名稱。

  2. 使用點陣圖編輯器建立 16∝16 圖示,如下所示。

    1. 在 [檢視] 功能表中,按一下 [屬性視窗]。

    2. 屬性 ] 視窗中,設定 高度寬度為 16。

    3. 您可以使用編輯器來建立圖示的影像。

  3. 方案總管] 中,點陣圖的項目,以滑鼠右鍵按一下,然後按一下 屬性

  4. 設定建置動作 屬性,以 內嵌資源

  5. 儲存所有開啟的檔案。

加入動態的工具箱組態提供者

本章節中,您需要建立並註冊的類別會實作IConfigureToolboxItem介面。 這個類別會具現化,而由Visual Studio整合式的開發環境 (IDE) 來設定工具箱控制項。

注意事項注意事項

因為Visual Studio環境會具現化之實作的執行個體IConfigureToolboxItem,不會實作IConfigureToolboxItem上實作的類別介面Package的 VSPackage。

建立並登錄的工具箱控制項組態物件

  1. 方案總管] 中、 將類別加入至 [ItemConfiguration] 專案,並命名為 ToolboxConfig。

  2. 將下列命名空間陳述式加入至檔案中。

    Imports Microsoft.VisualStudio.Shell
    Imports System.Collections
    Imports System.ComponentModel
    Imports System.Drawing.Design
    Imports System.Reflection
    Imports System.Runtime.InteropServices
    Imports System.Security.Permissions
    
    using Microsoft.VisualStudio.Shell;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    
  3. 請確定ToolboxConfig類別是public ,並實作IConfigureToolboxItem介面。

  4. Apply a GuidAttribute and a ProvideAssemblyFilterAttribute to the ToolboxConfig class.

    • 對於Visual Basic,使用組件名稱的 "ItemConfigurationVB,版本 = *,文化特性 = *,PublicKeyToken = * 」。

    • 對於Visual C#,使用組件名稱的 "ItemConfigurationCS,版本 = *,文化特性 = *,PublicKeyToken = * 」。

    如此一來,這會限定於ToolboxConfig類別正在進行的ToolboxItem所提供的組件,其中包含目前的 VSPackage 物件。

    <ProvideAssemblyFilter("ItemConfigurationVB, Version=*, Culture=*, PublicKeyToken=*")> _
    <Guid("4DDC7895-442A-45e7-82E7-4E85F243C321")> _
    Public Class ToolboxConfig
        Implements IConfigureToolboxItem
    
    [ProvideAssemblyFilter("ItemConfigurationCS, Version=*, Culture=*, PublicKeyToken=*")]
    [Guid("E6832593-BF07-4de1-AA0F-7F9B94887DB8")]
    public class ToolboxConfig : IConfigureToolboxItem
    

    您可以按一下 [產生的 GUID 建立 GUID工具功能表。 選取 [ 與矩形的格式在大括號,按一下 [ 複製,然後貼在程式碼中的 GUID。 變更關鍵字GUID到Guid。

  5. 實作ConfigureToolboxItem方法的IConfigureToolboxItem介面,讓方法都會作僅用於這兩個ToolboxItem類別, Control1和Control2。

    實作ConfigureToolboxItem適用於執行個體的ToolboxItemFilterAttribute兩個ToolboxItem物件,以便:

    • ToolboxItem ,由存取關聯式資料庫Control1才提供工具箱處理的設計工具的UserControl物件。

    • ToolboxItem ,由存取關聯式資料庫Control2不適用於工具箱處理的設計工具的UserControl物件。

    <PrincipalPermission(SecurityAction.Demand)> Public Sub _
        ConfigureToolboxItem(ByVal item As ToolboxItem) _
        Implements IConfigureToolboxItem.ConfigureToolboxItem
    
        If item Is Nothing Then Return 
    
        ' Create a filter for the Toolbox. 
        Dim newFilter As ToolboxItemFilterAttribute
        If GetType(Control1).ToString() = item.TypeName Then 
    
            ' For Control1, only show it when editing a UserControl.
            newFilter = New ToolboxItemFilterAttribute( _
                "System.Windows.Forms.UserControl", _
                ToolboxItemFilterType.Require)
    
        ElseIf GetType(Control2).ToString() = item.TypeName Then 
    
            ' For Control2, only show it when not editing a UserControl.
            newFilter = New ToolboxItemFilterAttribute( _
                "System.Windows.Forms.UserControl", _
                ToolboxItemFilterType.Prevent)
    
        Else 
    
            ' Don't apply a filter to other classes. 
            Return 
    
        End If
    
        item.Filter = CType(New ToolboxItemFilterAttribute() {newFilter}, ICollection)
    End Sub
    
    [PrincipalPermission(SecurityAction.Demand)]
    public void ConfigureToolboxItem(ToolboxItem item)
    {
        if (null == item) return;
    
        // Create a filter for the Toolbox.
        ToolboxItemFilterAttribute newFilter;
        if (typeof(Control1).ToString() == item.TypeName)
        {
            // For Control1, only show it when editing a UserControl.
            newFilter = new ToolboxItemFilterAttribute(
                "System.Windows.Forms.UserControl",
                ToolboxItemFilterType.Require);
        }
        else if (typeof(Control2).ToString() == item.TypeName)
        {
            // For Control2, only show it when not editing a UserControl.
            newFilter = new ToolboxItemFilterAttribute(
                "System.Windows.Forms.UserControl",
                ToolboxItemFilterType.Prevent);
        }
        else
        {
            // Don't apply a filter to other classes. 
            return;
        }
    
        item.Filter = (ICollection)(new ToolboxItemFilterAttribute[] { newFilter });
    }
    

修改 VSPackage 實作

預設的實作由 VSPackage Visual Studio必須修改封裝範本,以執行下列動作:

若要修改的工具箱項目提供者,在 VSPackage 上的封裝實作

  1. 在程式碼編輯器中開啟 ItemConfigurationPackage 類別。

  2. 修改宣告ItemConfigurationPackage類別,也就是實作的Package方案中的類別。

    1. 將下列命名空間陳述式加入至檔案中。

      Imports System.Collections
      Imports System.ComponentModel
      Imports System.Drawing.Design
      Imports System.Reflection
      
      using System.Collections;
      using System.ComponentModel;
      using System.Drawing.Design;
      using System.Reflection;
      
    2. 提供登錄 VSPackage 工具箱項目,套用ProvideToolboxItemsAttribute套件。 註冊ToolboxConfig類別提供工具箱來控制動態設定,套用ProvideToolboxItemConfigurationAttribute套件。

      ' ...
      <PackageRegistration(UseManagedResourcesOnly:=True), _
          DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0"), _
          InstalledProductRegistration(False, "#110", "#112", "1.0", IconResourceID:=400), _
          ProvideLoadKey("Standard", "1.0", "Package Name", "Company", 1), _
          ProvideMenuResource(1000, 1), _
          Guid(GuidList.guidItemConfigurationPkgString)> _
          <ProvideToolboxItems(1)> _
          <ProvideToolboxItemConfiguration(GetType(ToolboxConfig))> _
      Public NotInheritable Class DynamicToolboxMembersPackage
          Inherits Package
      
      // ...
      [PackageRegistration(UseManagedResourcesOnly = true)]
      // ...
      [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")]
      // ...
      [InstalledProductRegistration(false, "#110", "#112", "1.0", IconResourceID = 400)]
      // ...
      [ProvideLoadKey("Standard", "1.0", "Package Name", "Company", 1)]
      // ...
      [ProvideMenuResource(1000, 1)]
      [Guid(GuidList.guidItemConfigurationPkgString)]
      [ProvideToolboxItems(1)]
      [ProvideToolboxItemConfiguration(typeof(ToolboxConfig))]
      public sealed class DynamicToolboxMembersPackage : Package
      
      注意事項注意事項

      唯一的引數的ProvideToolboxItemsAttribute版本的ToolboxItem ,由 VSPackage。您可以藉由變更此值,強制載入 VSPackage,即使它附帶的更早版本的快取的版本 IDE ToolboxItem

    3. 建立兩個新private中的欄位ItemConfiguration類別,如下所示:

      ArrayList成員,名為ToolboxItemList,而保留一份ToolboxItem物件的ItemConfiguration類別會管理。

      A String、 具名CategoryTab,其中包含工具箱 ,用來容納索引標籤, ToolboxItem物件的ItemConfiguration類別會管理。

      Private ToolboxItemList As ArrayList
      Private Shared ReadOnly CategoryTab As String = _
          "ItemConfiguration Walkthrough VB"
      
      private ArrayList ToolboxItemList;
      private static readonly string CategoryTab =
          "ItemConfiguration Walkthrough CS";
      

    這項修改的結果會類似下列的程式碼:

    Imports Microsoft.VisualBasic
    Imports System
    Imports System.Diagnostics
    Imports System.Globalization
    Imports System.Runtime.InteropServices
    Imports System.ComponentModel.Design
    Imports Microsoft.Win32
    Imports Microsoft.VisualStudio.Shell.Interop
    Imports Microsoft.VisualStudio.OLE.Interop
    Imports Microsoft.VisualStudio.Shell
    
    Imports System.Collections
    Imports System.ComponentModel
    Imports System.Drawing.Design
    Imports System.Reflection
    
    ' ...
    <PackageRegistration(UseManagedResourcesOnly:=True), _
        DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0"), _
        InstalledProductRegistration(False, "#110", "#112", "1.0", IconResourceID:=400), _
        ProvideLoadKey("Standard", "1.0", "Package Name", "Company", 1), _
        ProvideMenuResource(1000, 1), _
        Guid(GuidList.guidItemConfigurationPkgString)> _
        <ProvideToolboxItems(1)> _
        <ProvideToolboxItemConfiguration(GetType(ToolboxConfig))> _
    Public NotInheritable Class DynamicToolboxMembersPackage
        Inherits Package
    
        Private ToolboxItemList As ArrayList
        Private Shared ReadOnly CategoryTab As String = _
            "ItemConfiguration Walkthrough VB" 
    
        ' ...
    
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.ComponentModel.Design;
    using Microsoft.Win32;
    using Microsoft.VisualStudio.Shell.Interop;
    using Microsoft.VisualStudio.OLE.Interop;
    using Microsoft.VisualStudio.Shell;
    
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Reflection;
    
    namespace Company.ItemConfigurationCS
    {
        // ...
        [PackageRegistration(UseManagedResourcesOnly = true)]
        // ...
        [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")]
        // ...
        [InstalledProductRegistration(false, "#110", "#112", "1.0", IconResourceID = 400)]
        // ...
        [ProvideLoadKey("Standard", "1.0", "Package Name", "Company", 1)]
        // ...
        [ProvideMenuResource(1000, 1)]
        [Guid(GuidList.guidItemConfigurationPkgString)]
        [ProvideToolboxItems(1)]
        [ProvideToolboxItemConfiguration(typeof(ToolboxConfig))]
        public sealed class DynamicToolboxMembersPackage : Package
        {
            private ArrayList ToolboxItemList;
            private static readonly string CategoryTab =
                "ItemConfiguration Walkthrough CS";
    
            // ...
    
  3. 定義OnRefreshToolbox方法來處理ToolboxInitializedToolboxUpgraded事件。

    OnRefreshToolbox方法會使用清單中的ToolboxItem中所包含的物件ToolboxItemList欄位,然後執行下列動作:

    • 會移除所有ToolboxItem將物件從工具箱 ] 索引標籤上所定義的CategoryTab欄位。

    • 若要將工具箱索引標籤上的所有新執行個體ToolboxItem中所列的物件ToolboxItemList欄位。

    • 設定工具箱與使用中的索引標籤] 索引標籤。

    ' Add new instances of all ToolboxItems to the toolbox item list. 
    Private Sub OnRefreshToolbox(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Me.ToolboxInitialized, Me.ToolboxUpgraded
    
        Dim service As IToolboxService = _
            TryCast(GetService(GetType(IToolboxService)), IToolboxService)
        Dim toolbox As IVsToolbox = _
             TryCast(GetService(GetType(IVsToolbox)), IVsToolbox)
    
        ' Remove target tab and all items under it. 
        For Each item As ToolboxItem In service.GetToolboxItems(CategoryTab)
            service.RemoveToolboxItem(item)
        Next
        toolbox.RemoveTab(CategoryTab)
    
        ' Recreate the target tab with the items from the current list.  
        For Each item As ToolboxItem In ToolboxItemList
            service.AddToolboxItem(item, CategoryTab)
        Next
        service.SelectedCategory = CategoryTab
    
        service.Refresh()
    End Sub
    
    // Add new instances of all ToolboxItems to the toolbox item list. 
    void OnRefreshToolbox(object sender, EventArgs e)
    {
        IToolboxService service =
            GetService(typeof(IToolboxService)) as IToolboxService;
        IVsToolbox toolbox =
            GetService(typeof(IVsToolbox)) as IVsToolbox;
    
        // Remove target tab and all items under it. 
        foreach (ToolboxItem item in service.GetToolboxItems(CategoryTab))
        {
            service.RemoveToolboxItem(item);
        }
        toolbox.RemoveTab(CategoryTab);
    
        // Recreate the target tab with the items from the current list.  
        foreach (ToolboxItem item in ToolboxItemList)
        {
            service.AddToolboxItem(item, CategoryTab);
        }
        service.SelectedCategory = CategoryTab;
    
        service.Refresh();
    }
    
  4. 對於Visual C#,在建構函式,註冊OnRefreshToolbox方法作為事件處理常式的ToolboxInitializedToolboxUpgraded事件。

    this.ToolboxInitialized += new EventHandler(OnRefreshToolbox);
    this.ToolboxUpgraded += new EventHandler(OnRefreshToolbox);
    
  5. 修改Initialize中的方法ItemConfigurationPackage來填滿ToolboxItemList欄位,藉由呼叫GetToolboxItems方法的ToolboxService類別。 工具箱 服務取得所有 工具箱項目目前正在執行的組件中所定義的類別。 ToolboxItemList欄位由工具箱事件處理常式,以載入工具箱項目。

    將下列程式碼加入 Initialize 方法的結尾。

    ' Use the toolbox service to get a list of all toolbox items in 
    ' this assembly.
    ToolboxItemList = New ArrayList( _
        ToolboxService.GetToolboxItems(Me.GetType().Assembly, ""))
    If ToolboxItemList Is Nothing Then 
        Throw New ApplicationException( _
            "Unable to generate a toolbox item listing for " & _
            Me.GetType().FullName)
    End If 
    
    ' Update the display name of each toolbox item in the list. 
    Dim thisAssembly As Assembly = Me.GetType().Assembly
    For Each item As ToolboxItem In ToolboxItemList
    
        Dim underlyingType As Type = thisAssembly.GetType(item.TypeName)
        Dim attribs As AttributeCollection = _
            TypeDescriptor.GetAttributes(underlyingType)
        Dim displayName As DisplayNameAttribute = _
            TryCast(attribs(GetType(DisplayNameAttribute)), DisplayNameAttribute)
    
        If displayName IsNot Nothing AndAlso Not displayName.IsDefaultAttribute() Then
            item.DisplayName = displayName.DisplayName
        End If 
    Next
    
    // Use the toolbox service to get a list of all toolbox items in 
    // this assembly.
    ToolboxItemList = new ArrayList(
        ToolboxService.GetToolboxItems(this.GetType().Assembly, ""));
    if (null == ToolboxItemList)
    {
        throw new ApplicationException(
            "Unable to generate a toolbox item listing for " +
            this.GetType().FullName);
    }
    
    // Update the display name of each toolbox item in the list.
    Assembly thisAssembly = this.GetType().Assembly;
    foreach (ToolboxItem item in ToolboxItemList)
    {
        Type underlyingType = thisAssembly.GetType(item.TypeName);
        AttributeCollection attribs =
            TypeDescriptor.GetAttributes(underlyingType);
        DisplayNameAttribute displayName =
            attribs[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
        if (displayName != null && !displayName.IsDefaultAttribute())
        {
            item.DisplayName = displayName.DisplayName;
        }
    }
    
    注意事項注意事項

    練習,其中一個可以開發一種機制,測試的新版的 VSPackage 或項目,並只更新 VSPackage 版本有所變更時,或如果版本的ToolboxItem已經變更。

正在初始化工具箱

若要實作命令,以初始化工具箱

  • 在ItemConfigurationPackage類別中,變更MenuItemCallBack方法,也就是該功能表項目的命令處理常式。

    取代現有的實作MenuItemCallBack藉由使用下列程式碼的方法:

    Private Sub MenuItemCallback(ByVal sender As Object, ByVal e As EventArgs)
        Dim pkg As IVsPackage = TryCast(GetService(GetType(Package)), IVsPackage)
        pkg.ResetDefaults(CUInt(__VSPKGRESETFLAGS.PKGRF_TOOLBOXITEMS))
    End Sub
    
    private void MenuItemCallback(object sender, EventArgs e)
    {
        IVsPackage pkg = GetService(typeof(Package)) as IVsPackage;
        pkg.ResetDefaults((uint)__VSPKGRESETFLAGS.PKGRF_TOOLBOXITEMS);
    }
    

建置和執行方案

藉由在實驗登錄區中執行的 Visual Studio 的執行個體,您可以運用這項逐步解說的乘積。

若要執行這項逐步解說

  1. 在 Visual Studio,在建置 ] 功能表中,按一下 重建方案

  2. 按 F5 以啟動的第二個執行個體Visual Studio的實驗登錄區中。

    如需有關如何使用實驗登錄區的詳細資訊,請參閱實驗性的執行個體的 Visual Studio

  3. 按一下 [工具] 功能表。

    命令,名為初始化 ItemConfiguration VB初始化 ItemConfiguration CS 上方的功能表中,加上有數字 1 的圖示會出現。

  4. 建立新的Visual C#或Visual Basic Windows Form 應用程式。

    A Form為基礎的設計工具隨即出現。

  5. 將使用者控制項加入至專案。

    使用者控制項設計工具就會出現。

  6. Pin 碼工具箱開啟,而且兩個設計檢視之間切換。

    請注意,其中工具箱項目為可見和隱藏的哪一個取決於哪一個設計工具取得焦點。

  7. 拖曳第一個工具箱項目放入的使用者控制項加入執行個體Control1加入使用者控制項。

  8. 拖曳第二個工具箱的執行個體加入至表單上的項目Control2至表單。

  9. 建置 Windows 應用程式。

    應用程式的使用者控制項現在是在工具箱

  10. 將應用程式的使用者控制項加入至表單,然後重建應用程式,並執行它。

    當應用程式執行時,請按一下表單,以取得相關聯的訊息方塊中的每一個控制項。

實作的分析

因為assemblyFilter參數是否存在於ProvideAssemblyFilterAttribute類別建構函式,只有ToolboxItem發生在這個逐步解說中所產生的組件中的物件作用ConfigureToolboxItem方法的ToolboxConfg類別。

因此,每當 ItemConfiguration 逐步解說類別正執行於工具箱ConfigureToolboxItem方法的ToolboxConfg呼叫類別時,以及ToolboxItemFilterAttribute執行個體適用於ToolboxItem物件實作的Control1和Control2。

請參閱

工作

進階的工具箱控制項開發

概念

正在註冊工具箱支援功能

其他資源

工具箱 (Visual Studio SDK)

工具箱的逐步解說