共用方式為


HOW TO:將智慧標籤附加至 Windows Form 元件

此範例將示範如何將智慧標籤支援加入到元件和自訂控制項中。

如需這個程式碼範例的完整說明,請參閱逐步解說:將智慧標籤加入至 Windows Form 元件

範例

'///////////////////////////////////////////////////////////////////
'Pull model smart tag example.
'Need references to System.dll, System.Windows.Forms.dll, 
' System.Design.dll, and System.Drawing.dll.
'///////////////////////////////////////////////////////////////////
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Windows.Forms
Imports System.Text
Imports System.Reflection

Namespace SmartTags

    Public Class Form1
        Inherits System.Windows.Forms.Form

        Private colorLabel2 As ColorLabel

        Public Sub New()
            InitializeComponent()
        End Sub

        'VS Forms Designer generated method
        Private Sub InitializeComponent()
            Me.colorLabel2 = New ColorLabel
            Me.SuspendLayout()
            '
            'colorLabel2
            '
            Me.colorLabel2.BackColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(165, Byte), Integer), CType(CType(0, Byte), Integer))
            Me.colorLabel2.ColorLocked = False
            Me.colorLabel2.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.colorLabel2.Location = New System.Drawing.Point(41, 42)
            Me.colorLabel2.Name = "colorLabel2"
            Me.colorLabel2.Size = New System.Drawing.Size(117, 25)
            Me.colorLabel2.TabIndex = 0
            Me.colorLabel2.Text = "ColorLabel"
            '
            'Form1
            '
            Me.ClientSize = New System.Drawing.Size(292, 273)
            Me.Controls.Add(Me.colorLabel2)
            Me.Name = "Form1"
            Me.ResumeLayout(False)

        End Sub

        <STAThread()> _
        Shared Sub Main()
            Dim f1 As New Form1()
            f1.ShowDialog()
        End Sub
    End Class


    '///////////////////////////////////////////////////////////////
    'ColorLabel is a simple extension of the standard Label control,
    ' with color property locking added.
    '///////////////////////////////////////////////////////////////
    <Designer(GetType(ColorLabelDesigner))> _
    Public Class ColorLabel
        Inherits System.Windows.Forms.Label

        Private colorLockedValue As Boolean = False

        Public Property ColorLocked() As Boolean
            Get
                Return colorLockedValue
            End Get
            Set(ByVal value As Boolean)
                colorLockedValue = value
            End Set
        End Property

        Public Overrides Property BackColor() As Color
            Get
                Return MyBase.BackColor
            End Get
            Set(ByVal value As Color)
                If ColorLocked Then
                    Return
                Else
                    MyBase.BackColor = value
                End If
            End Set
        End Property

        Public Overrides Property ForeColor() As Color
            Get
                Return MyBase.ForeColor
            End Get
            Set(ByVal value As Color)
                If ColorLocked Then
                    Return
                Else
                    MyBase.ForeColor = value
                End If
            End Set
        End Property
    End Class

    '///////////////////////////////////////////////////////////////
    'Designer for the ColorLabel control with support for a smart 
    ' tag panel.
    '///////////////////////////////////////////////////////////////
    'Must add reference to System.Design.dll
    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
    Public Class ColorLabelDesigner
        Inherits System.Windows.Forms.Design.ControlDesigner

        Private lists As DesignerActionListCollection

        'Use pull model to populate smart tag menu.
        Public Overrides ReadOnly Property ActionLists() _
        As DesignerActionListCollection
            Get
                If lists Is Nothing Then
                    lists = New DesignerActionListCollection()
                    lists.Add( _
                    New ColorLabelActionList(Me.Component))
                End If
                Return lists
            End Get
        End Property
    End Class

    '///////////////////////////////////////////////////////////////
    'DesignerActionList-derived class defines smart tag entries and
    ' resultant actions.
    '///////////////////////////////////////////////////////////////
    Public Class ColorLabelActionList
        Inherits System.ComponentModel.Design.DesignerActionList

        Private colLabel As ColorLabel

        Private designerActionUISvc As DesignerActionUIService = Nothing

        'The constructor associates the control 
        'with the smart tag list.
        Public Sub New(ByVal component As IComponent)

            MyBase.New(component)
            Me.colLabel = component

            ' Cache a reference to DesignerActionUIService, so the
            ' DesigneractionList can be refreshed.
            Me.designerActionUISvc = _
            CType(GetService(GetType(DesignerActionUIService)), _
            DesignerActionUIService)

        End Sub

        'Helper method to retrieve control properties. Use of 
        ' GetProperties enables undo and menu updates to work properly.
        Private Function GetPropertyByName(ByVal propName As String) _
        As PropertyDescriptor
            Dim prop As PropertyDescriptor
            prop = TypeDescriptor.GetProperties(colLabel)(propName)
            If prop Is Nothing Then
                Throw New ArgumentException( _
                "Matching ColorLabel property not found!", propName)
            Else
                Return prop
            End If
        End Function

        'Properties that are targets of DesignerActionPropertyItem entries.
        Public Property BackColor() As Color
            Get
                Return colLabel.BackColor
            End Get
            Set(ByVal value As Color)
                GetPropertyByName("BackColor").SetValue(colLabel, value)
            End Set
        End Property

        Public Property ForeColor() As Color
            Get
                Return colLabel.ForeColor
            End Get
            Set(ByVal value As Color)
                GetPropertyByName("ForeColor").SetValue(colLabel, value)
            End Set
        End Property

        'Boolean properties are automatically displayed with binary 
        ' UI (such as a checkbox).
        Public Property LockColors() As Boolean
            Get
                Return colLabel.ColorLocked
            End Get
            Set(ByVal value As Boolean)
                GetPropertyByName("ColorLocked").SetValue(colLabel, value)

                ' Refresh the list.
                Me.designerActionUISvc.Refresh(Me.Component)
            End Set
        End Property

        Public Property [Text]() As String
            Get
                Return colLabel.Text
            End Get
            Set(ByVal value As String)
                GetPropertyByName("Text").SetValue(colLabel, value)
            End Set
        End Property


        'Method that is target of a DesignerActionMethodItem
        Public Sub InvertColors()
            Dim currentBackColor As Color = colLabel.BackColor
            BackColor = Color.FromArgb( _
            255 - currentBackColor.R, _
            255 - currentBackColor.G, _
            255 - currentBackColor.B)

            Dim currentForeColor As Color = colLabel.ForeColor
            ForeColor = Color.FromArgb( _
            255 - currentForeColor.R, _
            255 - currentForeColor.G, _
            255 - currentForeColor.B)
        End Sub

        'Implementation of this virtual method creates smart tag  
        ' items, associates their targets, and collects into list.
        Public Overrides Function GetSortedActionItems() _
        As DesignerActionItemCollection
            Dim items As New DesignerActionItemCollection()

            'Define static section header entries.
            items.Add(New DesignerActionHeaderItem("Appearance"))
            items.Add(New DesignerActionHeaderItem("Information"))

            'Boolean property for locking color selections.
            items.Add(New DesignerActionPropertyItem( _
            "LockColors", _
            "Lock Colors", _
            "Appearance", _
            "Locks the color properties."))

            If Not LockColors Then
                items.Add( _
                New DesignerActionPropertyItem( _
                "BackColor", _
                "Back Color", _
                "Appearance", _
                "Selects the background color."))

                items.Add( _
                New DesignerActionPropertyItem( _
                "ForeColor", _
                "Fore Color", _
                "Appearance", _
                "Selects the foreground color."))

                'This next method item is also added to the context menu 
                ' (as a designer verb).
                items.Add( _
                New DesignerActionMethodItem( _
                Me, _
                "InvertColors", _
                "Invert Colors", _
                "Appearance", _
                "Inverts the fore and background colors.", _
                True))
            End If
            items.Add( _
            New DesignerActionPropertyItem( _
            "Text", _
            "Text String", _
            "Appearance", _
            "Sets the display text."))

            'Create entries for static Information section.
            Dim location As New StringBuilder("Location: ")
            location.Append(colLabel.Location)
            Dim size As New StringBuilder("Size: ")
            size.Append(colLabel.Size)

            items.Add( _
            New DesignerActionTextItem( _
            location.ToString(), _
            "Information"))

            items.Add( _
            New DesignerActionTextItem( _
            size.ToString(), _
            "Information"))

            Return items
        End Function

    End Class
End Namespace
/////////////////////////////////////////////////////////////////////
// Pull model smart tag example.
// Need references to System.dll, System.Windows.Forms.dll, 
// System.Design.dll, and System.Drawing.dll.
/////////////////////////////////////////////////////////////////////

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Text;
using System.Reflection;


namespace SmartTags
{

public class Form1 : System.Windows.Forms.Form
{
    private ColorLabel colorLabel2;

    public Form1()
    {
        InitializeComponent();
    }

    // VS Forms Designer generated method
    private void InitializeComponent()
    {
        this.colorLabel2 = new SmartTags.ColorLabel();
        this.SuspendLayout();
        // 
        // colorLabel2
        // 
        this.colorLabel2.BackColor = System.Drawing.Color.Gold;
        this.colorLabel2.ColorLocked = false;
        this.colorLabel2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.colorLabel2.Location = new System.Drawing.Point(41, 42);
        this.colorLabel2.Name = "colorLabel2";
        this.colorLabel2.Size = new System.Drawing.Size(117, 25);
        this.colorLabel2.TabIndex = 0;
        this.colorLabel2.Text = "colorLabel2";
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.Add(this.colorLabel2);
        this.Name = "Form1";
        this.ResumeLayout(false);

    }

    [STAThread]
    static void Main()
    {
        Form1 f1 = new Form1();
        f1.ShowDialog();
    }


}

/////////////////////////////////////////////////////////////////
// ColorLabel is a simple extension of the standard Label control,
// with color property locking added.
/////////////////////////////////////////////////////////////////
[Designer(typeof(ColorLabelDesigner))]
public class ColorLabel : System.Windows.Forms.Label
{
    private bool colorLockedValue = false;

    public bool ColorLocked
    {
        get
        {
            return colorLockedValue;
        }
        set
        {
            colorLockedValue = value;
        }
    }

    public override Color BackColor
    {
        get
        {
            return base.BackColor;
        }
        set
        {
            if (ColorLocked)
                return;
            else
                base.BackColor = value;
        }
    }

    public override Color ForeColor
    {
        get
        {
            return base.ForeColor;
        }
        set
        {
            if (ColorLocked)
                return;
            else
                base.ForeColor = value;
        }
    }
}

/////////////////////////////////////////////////////////////////
// Designer for the ColorLabel control with support for a smart 
// tag panel.
// Must add reference to System.Design.dll
/////////////////////////////////////////////////////////////////
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] 
public class ColorLabelDesigner : 
         System.Windows.Forms.Design.ControlDesigner
{
    private DesignerActionListCollection actionLists;

    // Use pull model to populate smart tag menu.
    public override DesignerActionListCollection ActionLists
    {
        get
        {
            if (null == actionLists)
            {
                actionLists = new DesignerActionListCollection();
                actionLists.Add(
                    new ColorLabelActionList(this.Component));
            }
            return actionLists;
        }
    }
}

/////////////////////////////////////////////////////////////////
// DesignerActionList-derived class defines smart tag entries and
// resultant actions.
/////////////////////////////////////////////////////////////////
public class ColorLabelActionList :
          System.ComponentModel.Design.DesignerActionList
{
    private ColorLabel colLabel;

    private DesignerActionUIService designerActionUISvc = null;

    //The constructor associates the control 
    //with the smart tag list.
    public ColorLabelActionList( IComponent component ) : base(component) 
    {
        this.colLabel = component as ColorLabel;

        // Cache a reference to DesignerActionUIService, so the
        // DesigneractionList can be refreshed.
        this.designerActionUISvc =
            GetService(typeof(DesignerActionUIService))
            as DesignerActionUIService;
    }

    // Helper method to retrieve control properties. Use of 
    // GetProperties enables undo and menu updates to work properly.
    private PropertyDescriptor GetPropertyByName(String propName)
    {
        PropertyDescriptor prop;
        prop = TypeDescriptor.GetProperties(colLabel)[propName];
        if (null == prop)
             throw new ArgumentException(
                  "Matching ColorLabel property not found!",
                   propName);
        else
            return prop;
    }

    // Properties that are targets of DesignerActionPropertyItem entries.
    public Color BackColor
    {
        get
        {
            return colLabel.BackColor;
        }
        set
        {
            GetPropertyByName("BackColor").SetValue(colLabel, value);
        }
    }

    public Color ForeColor
    {
        get
        {
            return colLabel.ForeColor;
        }
        set
        {
            GetPropertyByName("ForeColor").SetValue(colLabel, value);
        }
    }


    // Boolean properties are automatically displayed with binary 
    // UI (such as a checkbox).
    public bool LockColors
    {
        get
        {
            return colLabel.ColorLocked;
        }
        set
        {
            GetPropertyByName("ColorLocked").SetValue(colLabel, value);

            // Refresh the list.
            this.designerActionUISvc.Refresh(this.Component);
        }
    }

    public String Text
    {
        get
        {
            return colLabel.Text;
        }
        set
        {
            GetPropertyByName("Text").SetValue(colLabel, value);
        }
    }

    // Method that is target of a DesignerActionMethodItem
    public void InvertColors()
    {
        Color currentBackColor = colLabel.BackColor;
        BackColor = Color.FromArgb(
            255 - currentBackColor.R, 
            255 - currentBackColor.G, 
            255 - currentBackColor.B);

        Color currentForeColor = colLabel.ForeColor;
        ForeColor = Color.FromArgb(
            255 - currentForeColor.R, 
            255 - currentForeColor.G, 
            255 - currentForeColor.B);
    }

    // Implementation of this abstract method creates smart tag  
    // items, associates their targets, and collects into list.
    public override DesignerActionItemCollection GetSortedActionItems()
    {
        DesignerActionItemCollection items = new DesignerActionItemCollection();

        //Define static section header entries.
        items.Add(new DesignerActionHeaderItem("Appearance"));
        items.Add(new DesignerActionHeaderItem("Information"));

        //Boolean property for locking color selections.
        items.Add(new DesignerActionPropertyItem("LockColors",
                         "Lock Colors", "Appearance",
                         "Locks the color properties."));
        if (!LockColors)
        {
            items.Add(new DesignerActionPropertyItem("BackColor",
                             "Back Color", "Appearance",
                             "Selects the background color."));
            items.Add(new DesignerActionPropertyItem("ForeColor",
                             "Fore Color", "Appearance",
                             "Selects the foreground color."));

            //This next method item is also added to the context menu 
            // (as a designer verb).
            items.Add(new DesignerActionMethodItem(this,
                             "InvertColors", "Invert Colors",
                             "Appearance",
                             "Inverts the fore and background colors.",
                              true));
        }
        items.Add(new DesignerActionPropertyItem("Text",
                         "Text String", "Appearance",
                         "Sets the display text."));

        //Create entries for static Information section.
        StringBuilder location = new StringBuilder("Location: ");
        location.Append(colLabel.Location);
        StringBuilder size = new StringBuilder("Size: ");
        size.Append(colLabel.Size);
        items.Add(new DesignerActionTextItem(location.ToString(),
                         "Information"));
        items.Add(new DesignerActionTextItem(size.ToString(),
                         "Information"));

        return items;
    }
}


}

編譯程式碼

每當您對元件的設計階段方面進行變更時,必須重新建置控制項專案。此外,如果目前有開啟另一個 Windows Form 專案,而且該專案使用這個元件,您可能需要重新整理專案才能看到變更。您通常必須先關閉包含元件的設計視窗,然後再重新開啟一次。

注意事項注意事項

您必須加入對設計階段組件 (System.Design.dll) 的參考。這個組件未包含在 .NET Framework 4 Client Profile 中。若要加入對 System.Design.dll 的參考,您必須將專案的目標 Framework 變更為 [.NET Framework 4]。

請參閱

參考

DesignerVerb

DesignerActionItem

DesignerActionList

ActionLists

DesignerActionService

概念

Windows Form 的設計工具命令和 DesignerAction 物件模型

其他資源

擴充設計階段支援