ToolStripItem 类  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示对 ToolStrip 或 ToolStripDropDown 可以包含的所有元素的事件和布局进行管理的抽象基类。
public ref class ToolStripItem abstract : System::ComponentModel::Component, IDisposable, System::Windows::Forms::IDropTargetpublic ref class ToolStripItem abstract : System::Windows::Forms::BindableComponent, IDisposable, System::Windows::Forms::IDropTargetpublic abstract class ToolStripItem : System.ComponentModel.Component, IDisposable, System.Windows.Forms.IDropTargetpublic abstract class ToolStripItem : System.Windows.Forms.BindableComponent, IDisposable, System.Windows.Forms.IDropTargettype ToolStripItem = class
    inherit Component
    interface IDropTarget
    interface IComponent
    interface IDisposabletype ToolStripItem = class
    inherit BindableComponent
    interface IDropTarget
    interface IComponent
    interface IDisposablePublic MustInherit Class ToolStripItem
Inherits Component
Implements IDisposable, IDropTargetPublic MustInherit Class ToolStripItem
Inherits BindableComponent
Implements IDisposable, IDropTarget- 继承
- 继承
- 派生
- 实现
示例
下面的代码示例演示如何实现自定义 ToolStripItem 控件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace RolloverItemDemoLib
{
    // This class implements a ToolStripItem that highlights
    // its border and text when the mouse enters its
    // client rectangle. It has a clickable state which is
    // exposed through the Clicked property and displayed
    // by highlighting or graying out the item's image. 
    public class RolloverItem : ToolStripItem
    {
        private bool clickedValue = false;
        private bool rolloverValue = false;
        private Rectangle imageRect;
        private Rectangle textRect;
        // For brevity, this implementation limits the possible 
        // TextDirection values to ToolStripTextDirection.Horizontal. 
        public override ToolStripTextDirection TextDirection
        {
            get
            {
                return base.TextDirection;
            }
            set
            {
                if (value == ToolStripTextDirection.Horizontal)
                {
                    base.TextDirection = value;
                }
                else
                {
                    throw new ArgumentException(
                        "RolloverItem supports only horizontal text.");
                }
            }
        }
        // For brevity, this implementation limits the possible 
        // TextImageRelation values to ImageBeforeText and TextBeforeImage. 
        public new TextImageRelation TextImageRelation
        {
            get
            {
                return base.TextImageRelation;
            }
            set
            {
                if (value == TextImageRelation.ImageBeforeText || 
                    value == TextImageRelation.TextBeforeImage)
                {
                    base.TextImageRelation = value;
                }
                else
                {
                    throw new ArgumentException(
                        "Unsupported TextImageRelation value.");
                }
            }
        }
        
        // This property returns true if the mouse is 
        // inside the client rectangle.
        public bool Rollover
        {
            get
            {
                return this.rolloverValue;
            }   
        }
        // This property returns true if the item 
        // has been toggled into the clicked state.
        // Clicking again toggles it to the 
        // unclicked state.
        public bool Clicked
        {
            get
            {
                return this.clickedValue;
            }
        }
        // The method defines the behavior of the Click event.
        // It simply toggles the state of the clickedValue field.
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
            this.clickedValue ^= true;
        }
        // The method defines the behavior of the DoubleClick 
        // event. It shows a MessageBox with the item's text.
        protected override void OnDoubleClick(EventArgs e)
        {
            base.OnDoubleClick(e);
            string msg = String.Format("Item: {0}", this.Text);
            MessageBox.Show(msg);
        }
        // This method defines the behavior of the MouseEnter event.
        // It sets the state of the rolloverValue field to true and
        // tells the control to repaint.
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            this.rolloverValue = true;
            this.Invalidate();
        }
        // This method defines the behavior of the MouseLeave event.
        // It sets the state of the rolloverValue field to false and
        // tells the control to repaint.
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            this.rolloverValue = false;
            this.Invalidate();
        }
        // This method defines the painting behavior of the control.
        // It performs the following operations:
        //
        // Computes the layout of the item's image and text.
        // Draws the item's background image.
        // Draws the item's image.
        // Draws the item's text.
        //
        // Drawing operations are implemented in the 
        // RolloverItemRenderer class.
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (this.Owner != null)
            {
                // Find the dimensions of the image and the text 
                // areas of the item. 
                this.ComputeImageAndTextLayout();
                // Draw the background. This includes drawing a highlighted 
                // border when the mouse is in the client area.
                ToolStripItemRenderEventArgs ea = new ToolStripItemRenderEventArgs(
                     e.Graphics,
                     this);
                this.Owner.Renderer.DrawItemBackground(ea);
                // Draw the item's image. 
                ToolStripItemImageRenderEventArgs irea =
                    new ToolStripItemImageRenderEventArgs(
                    e.Graphics,
                    this,
                    imageRect );
                this.Owner.Renderer.DrawItemImage(irea);
                // If the item is on a drop-down, give its
                // text a different highlighted color.
                Color highlightColor = 
                    this.IsOnDropDown ?
                    Color.Salmon : SystemColors.ControlLightLight;
                // Draw the text, and highlight it if the 
                // the rollover state is true.
                ToolStripItemTextRenderEventArgs rea =
                    new ToolStripItemTextRenderEventArgs(
                    e.Graphics,
                    this,
                    base.Text,
                    textRect,
                    this.rolloverValue ? highlightColor : base.ForeColor,
                    base.Font,
                    base.TextAlign);
                this.Owner.Renderer.DrawItemText(rea);
            }
        }
        // This utility method computes the layout of the 
        // RolloverItem control's image area and the text area.
        // For brevity, only the following settings are 
        // supported:
        //
        // ToolStripTextDirection.Horizontal
        // TextImageRelation.ImageBeforeText 
        // TextImageRelation.ImageBeforeText
        // 
        // It would not be difficult to support vertical text
        // directions and other image/text relationships.
        private void ComputeImageAndTextLayout()
        {
            Rectangle cr = base.ContentRectangle;
            Image img = base.Owner.ImageList.Images[base.ImageKey];
            // Compute the center of the item's ContentRectangle.
            int centerY = (cr.Height - img.Height) / 2;
            // Find the dimensions of the image and the text 
            // areas of the item. The text occupies the space 
            // not filled by the image. 
            if (base.TextImageRelation == TextImageRelation.ImageBeforeText &&
                base.TextDirection == ToolStripTextDirection.Horizontal)
            {
                imageRect = new Rectangle(
                    base.ContentRectangle.Left,
                    centerY,
                    base.Image.Width,
                    base.Image.Height);
                textRect = new Rectangle(
                    imageRect.Width,
                    base.ContentRectangle.Top,
                    base.ContentRectangle.Width - imageRect.Width,
                    base.ContentRectangle.Height);
            }
            else if (base.TextImageRelation == TextImageRelation.TextBeforeImage &&
                     base.TextDirection == ToolStripTextDirection.Horizontal)
            {
                imageRect = new Rectangle(
                    base.ContentRectangle.Right - base.Image.Width,
                    centerY,
                    base.Image.Width,
                    base.Image.Height);
                textRect = new Rectangle(
                    base.ContentRectangle.Left,
                    base.ContentRectangle.Top,
                    imageRect.X,
                    base.ContentRectangle.Bottom);
            }
        }
    }
    #region RolloverItemRenderer
    // This is the custom renderer for the RolloverItem control.
    // It draws a border around the item when the mouse is
    // in the item's client area. It also draws the item's image
    // in an inactive state (grayed out) until the user clicks
    // the item to toggle its "clicked" state.
    internal class RolloverItemRenderer : ToolStripSystemRenderer
    {
        protected override void OnRenderItemImage(
            ToolStripItemImageRenderEventArgs e)
        {
            base.OnRenderItemImage(e);
            RolloverItem item = e.Item as RolloverItem;
            // If the ToolSTripItem is of type RolloverItem, 
            // perform custom rendering for the image.
            if (item != null)
            {
                if (item.Clicked)
                {
                    // The item is in the clicked state, so 
                    // draw the image as usual.
                    e.Graphics.DrawImage(
                        e.Image,
                        e.ImageRectangle.X,
                        e.ImageRectangle.Y);
                }
                else
                {
                    // In the unclicked state, gray out the image.
                    ControlPaint.DrawImageDisabled(
                        e.Graphics,
                        e.Image,
                        e.ImageRectangle.X,
                        e.ImageRectangle.Y,
                        item.BackColor);
                }
            }
        }
        // This method defines the behavior for rendering the
        // background of a ToolStripItem. If the item is a
        // RolloverItem, it paints the item's BackgroundImage 
        // centered in the client area. If the mouse is in the 
        // item's client area, a border is drawn around it.
        // If the item is on a drop-down or if it is on the
        // overflow, a gradient is painted in the background.
        protected override void OnRenderItemBackground(
            ToolStripItemRenderEventArgs e)
        {
            base.OnRenderItemBackground(e);
            RolloverItem item = e.Item as RolloverItem;
            // If the ToolSTripItem is of type RolloverItem, 
            // perform custom rendering for the background.
            if (item != null)
            {
                if (item.Placement == ToolStripItemPlacement.Overflow ||
                    item.IsOnDropDown)
                {
                    using (LinearGradientBrush b = new LinearGradientBrush(
                        item.ContentRectangle,
                        Color.Salmon,
                        Color.DarkRed,
                        0f,
                        false))
                    {
                        e.Graphics.FillRectangle(b, item.ContentRectangle);
                    }
                }
                // The RolloverItem control only supports 
                // the ImageLayout.Center setting for the
                // BackgroundImage property.
                if (item.BackgroundImageLayout == ImageLayout.Center)
                {
                    // Get references to the item's ContentRectangle
                    // and BackgroundImage, for convenience.
                    Rectangle cr = item.ContentRectangle;
                    Image bgi = item.BackgroundImage;
                    // Compute the center of the item's ContentRectangle.
                    int centerX = (cr.Width - bgi.Width) / 2;
                    int centerY = (cr.Height - bgi.Height) / 2;
                    // If the item is selected, draw the background
                    // image as usual. Otherwise, draw it as disabled.
                    if (item.Selected)
                    {
                        e.Graphics.DrawImage(bgi, centerX, centerY);
                    }
                    else
                    {
                        ControlPaint.DrawImageDisabled(
                                e.Graphics,
                                bgi,
                                centerX,
                                centerY,
                                item.BackColor);
                    }
                }
                // If the item is in the rollover state, 
                // draw a border around it.
                if (item.Rollover)
                {
                    ControlPaint.DrawFocusRectangle(
                        e.Graphics,
                        item.ContentRectangle);
                }
            }
        }
    #endregion
    }
    // This form tests various features of the RolloverItem
    // control. RolloverItem conrols are created and added
    // to the form's ToolStrip. They are also created and 
    // added to a button's ContextMenuStrip. The behavior
    // of the RolloverItem control differs depending on 
    // the type of parent control.
    public class RolloverItemTestForm : Form
    {
        private System.Windows.Forms.ToolStrip toolStrip1;
        private System.Windows.Forms.Button button1;
        private string infoIconKey = "Information icon";
        private string handIconKey = "Hand icon";
        private string exclIconKey = "Exclamation icon";
        private string questionIconKey = "Question icon";
        private string warningIconKey = "Warning icon ";
        private System.ComponentModel.IContainer components = null;
        public RolloverItemTestForm()
        {
            InitializeComponent();
            // Set up the form's ToolStrip control.
            InitializeToolStrip();
            // Set up the ContextMenuStrip for the button.
            InitializeContextMenu();
        }
        // This utility method initializes the ToolStrip control's 
        // image list. For convenience, icons from the SystemIcons 
        // class are used for this demonstration, but any images
        // could be used.
        private void InitializeImageList(ToolStrip ts)
        {
            if (ts.ImageList == null)
            {
                ts.ImageList = new ImageList();
                ts.ImageList.ImageSize = SystemIcons.Exclamation.Size;
                ts.ImageList.Images.Add(
                    this.infoIconKey,
                    SystemIcons.Information);
                ts.ImageList.Images.Add(
                    this.handIconKey,
                    SystemIcons.Hand);
                ts.ImageList.Images.Add(
                    this.exclIconKey,
                    SystemIcons.Exclamation);
                ts.ImageList.Images.Add(
                    this.questionIconKey,
                    SystemIcons.Question);
                ts.ImageList.Images.Add(
                    this.warningIconKey,
                    SystemIcons.Warning);
            }
        }
        private void InitializeToolStrip()
        {
            this.InitializeImageList(this.toolStrip1);
            this.toolStrip1.Renderer = new RolloverItemRenderer();
            RolloverItem item = this.CreateRolloverItem(
                this.toolStrip1,
                "RolloverItem on ToolStrip",
                this.Font,
                infoIconKey,
                TextImageRelation.ImageBeforeText,
                exclIconKey);
            this.toolStrip1.Items.Add(item);
            item = this.CreateRolloverItem(
                this.toolStrip1,
                "RolloverItem on ToolStrip",
                this.Font,
                infoIconKey,
                TextImageRelation.ImageBeforeText,
                exclIconKey);
            this.toolStrip1.Items.Add(item);
        }
        private void InitializeContextMenu()
        {
            Font f = new System.Drawing.Font(
                "Arial",
                18f,
                FontStyle.Bold);
            ContextMenuStrip cms = new ContextMenuStrip();
            this.InitializeImageList(cms);
            cms.Renderer = new RolloverItemRenderer();
            cms.AutoSize = true;
            cms.ShowCheckMargin = false;
            cms.ShowImageMargin = false;
            RolloverItem item = this.CreateRolloverItem(
                cms,
                "RolloverItem on ContextMenuStrip",
                f,
                handIconKey,
                TextImageRelation.ImageBeforeText,
                exclIconKey);
            cms.Items.Add(item);
            item = this.CreateRolloverItem(
                cms,
                "Another RolloverItem on ContextMenuStrip",
                f,
                questionIconKey,
                TextImageRelation.ImageBeforeText,
                exclIconKey);
            cms.Items.Add(item);
            item = this.CreateRolloverItem(
                cms,
                "And another RolloverItem on ContextMenuStrip",
                f,
                warningIconKey,
                TextImageRelation.ImageBeforeText,
                exclIconKey);
            cms.Items.Add(item);
            cms.Closing += new ToolStripDropDownClosingEventHandler(cms_Closing);
            this.button1.ContextMenuStrip = cms;
        }
        // This method handles the ContextMenuStrip 
        // control's Closing event. It prevents the 
        // RolloverItem from closing the drop-down  
        // when the item is clicked.
        void cms_Closing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
            {
                e.Cancel = true;
            }
        }
        // This method handles the Click event for the button.
        // it selects the first item in the ToolStrip control
        // by using the ToolStripITem.Select method.
        private void button1_Click(object sender, EventArgs e)
        {
            RolloverItem item = this.toolStrip1.Items[0] as RolloverItem;
            if (item != null)
            {
                item.Select();
                this.Invalidate();
            }
        }
        // This utility method creates a RolloverItem 
        // and adds it to a ToolStrip control.
        private RolloverItem CreateRolloverItem(
            ToolStrip owningToolStrip,
            string txt,
            Font f,
            string imgKey,
            TextImageRelation tir,
            string backImgKey)
        {
            RolloverItem item = new RolloverItem();
            item.Alignment = ToolStripItemAlignment.Left;
            item.AllowDrop = false;
            item.AutoSize = true;
            item.BackgroundImage = owningToolStrip.ImageList.Images[backImgKey];
            item.BackgroundImageLayout = ImageLayout.Center;
            item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            item.DoubleClickEnabled = true;
            item.Enabled = true;
            item.Font = f;
            // These assignments are equivalent. Each assigns an
            // image from the owning toolstrip's image list.
            item.ImageKey = imgKey;
            //item.Image = owningToolStrip.ImageList.Images[infoIconKey];
            //item.ImageIndex = owningToolStrip.ImageList.Images.IndexOfKey(infoIconKey);
            item.ImageScaling = ToolStripItemImageScaling.None;
            item.Owner = owningToolStrip;
            item.Padding = new Padding(2);
            item.Text = txt;
            item.TextAlign = ContentAlignment.MiddleLeft;
            item.TextDirection = ToolStripTextDirection.Horizontal;
            item.TextImageRelation = tir;
            return item;
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows Form Designer generated code
        private void InitializeComponent()
        {
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // toolStrip1
            // 
            this.toolStrip1.AllowItemReorder = true;
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(845, 25);
            this.toolStrip1.TabIndex = 0;
            this.toolStrip1.Text = "toolStrip1";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 100);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(86, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Click to select";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // RolloverItemTestForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.ClientSize = new System.Drawing.Size(845, 282);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.toolStrip1);
            this.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "RolloverItemTestForm";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion
    }
    static class Program
    {   
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new RolloverItemTestForm());
        }
    }
}
Option Strict On
Option Explicit On
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
' This class implements a ToolStripItem that highlights
' its border and text when the mouse enters its
' client rectangle. It has a clickable state which is
' exposed through the Clicked property and displayed
' by highlighting or graying out the item's image. 
Public Class RolloverItem
    Inherits ToolStripItem
   Private clickedValue As Boolean = False
   Private rolloverValue As Boolean = False
   
   Private imageRect As Rectangle
   Private textRect As Rectangle
   
   ' For brevity, this implementation limits the possible 
   ' TextDirection values to ToolStripTextDirection.Horizontal. 
   Public Overrides Property TextDirection() As ToolStripTextDirection
      Get
         Return MyBase.TextDirection
      End Get
      Set
         If value = ToolStripTextDirection.Horizontal Then
            MyBase.TextDirection = value
         Else
                Throw New ArgumentException( _
                "RolloverItem supports only horizontal text.")
         End If
      End Set
   End Property
   
   ' For brevity, this implementation limits the possible 
   ' TextImageRelation values to ImageBeforeText and TextBeforeImage. 
   Public Shadows Property TextImageRelation() As TextImageRelation
      Get
         Return MyBase.TextImageRelation
      End Get
      
      Set
            If Value = TextImageRelation.ImageBeforeText OrElse _
               Value = TextImageRelation.TextBeforeImage Then
                MyBase.TextImageRelation = Value
            Else
                Throw New ArgumentException("Unsupported TextImageRelation value.")
            End If
      End Set
   End Property
   
   ' This property returns true if the mouse is 
   ' inside the client rectangle.
   Public ReadOnly Property Rollover() As Boolean
      Get
         Return Me.rolloverValue
      End Get
    End Property
   ' This property returns true if the item 
   ' has been toggled into the clicked state.
   ' Clicking again toggles it to the 
   ' unclicked state.
   Public ReadOnly Property Clicked() As Boolean
      Get
         Return Me.clickedValue
      End Get
   End Property
   
   ' The method defines the behavior of the Click event.
   ' It simply toggles the state of the clickedValue field.
   Protected Overrides Sub OnClick(e As EventArgs)
      MyBase.OnClick(e)
      
        Me.clickedValue = Me.clickedValue Xor True
    End Sub
   ' The method defines the behavior of the DoubleClick 
   ' event. It shows a MessageBox with the item's text.
   Protected Overrides Sub OnDoubleClick(e As EventArgs)
      MyBase.OnDoubleClick(e)
      
      Dim msg As String = String.Format("Item: {0}", Me.Text)
      
      MessageBox.Show(msg)
    End Sub
   ' This method defines the behavior of the MouseEnter event.
   ' It sets the state of the rolloverValue field to true and
   ' tells the control to repaint.
   Protected Overrides Sub OnMouseEnter(e As EventArgs)
      MyBase.OnMouseEnter(e)
      
      Me.rolloverValue = True
      
      Me.Invalidate()
    End Sub
   
   ' This method defines the behavior of the MouseLeave event.
   ' It sets the state of the rolloverValue field to false and
   ' tells the control to repaint.
   Protected Overrides Sub OnMouseLeave(e As EventArgs)
      MyBase.OnMouseLeave(e)
      
      Me.rolloverValue = False
      
      Me.Invalidate()
    End Sub
   
   ' This method defines the painting behavior of the control.
   ' It performs the following operations:
   '
   ' Computes the layout of the item's image and text.
   ' Draws the item's background image.
   ' Draws the item's image.
   ' Draws the item's text.
   '
   ' Drawing operations are implemented in the 
   ' RolloverItemRenderer class.
   Protected Overrides Sub OnPaint(e As PaintEventArgs)
      MyBase.OnPaint(e)
      
      If (Me.Owner IsNot Nothing) Then
         ' Find the dimensions of the image and the text 
         ' areas of the item. 
         Me.ComputeImageAndTextLayout()
         
         ' Draw the background. This includes drawing a highlighted 
         ' border when the mouse is in the client area.
         Dim ea As New ToolStripItemRenderEventArgs(e.Graphics, Me)
         Me.Owner.Renderer.DrawItemBackground(ea)
         
         ' Draw the item's image. 
         Dim irea As New ToolStripItemImageRenderEventArgs(e.Graphics, Me, imageRect)
         Me.Owner.Renderer.DrawItemImage(irea)
         
         ' If the item is on a drop-down, give its
         ' text a different highlighted color.
            Dim highlightColor As Color = CType(IIf(Me.IsOnDropDown, Color.Salmon, SystemColors.ControlLightLight), Color)
         
         ' Draw the text, and highlight it if the 
         ' the rollover state is true.
            Dim rea As New ToolStripItemTextRenderEventArgs( _
               e.Graphics, _
               Me, _
               MyBase.Text, _
               textRect, _
               CType(IIf(Me.rolloverValue, highlightColor, MyBase.ForeColor), Color), _
               MyBase.Font, _
               MyBase.TextAlign)
         Me.Owner.Renderer.DrawItemText(rea)
      End If
    End Sub
   ' This utility method computes the layout of the 
   ' RolloverItem control's image area and the text area.
   ' For brevity, only the following settings are 
   ' supported:
   '
   ' ToolStripTextDirection.Horizontal
   ' TextImageRelation.ImageBeforeText 
   ' TextImageRelation.ImageBeforeText
   ' 
   ' It would not be difficult to support vertical text
   ' directions and other image/text relationships.
   Private Sub ComputeImageAndTextLayout()
      Dim cr As Rectangle = MyBase.ContentRectangle
      Dim img As Image = MyBase.Owner.ImageList.Images(MyBase.ImageKey)
      
      ' Compute the center of the item's ContentRectangle.
        Dim centerY As Integer = CInt((cr.Height - img.Height) / 2)
      
      ' Find the dimensions of the image and the text 
      ' areas of the item. The text occupies the space 
      ' not filled by the image. 
        If MyBase.TextImageRelation = _
        TextImageRelation.ImageBeforeText AndAlso _
        MyBase.TextDirection = ToolStripTextDirection.Horizontal Then
            imageRect = New Rectangle( _
            MyBase.ContentRectangle.Left, _
            centerY, _
            MyBase.Image.Width, _
            MyBase.Image.Height)
            textRect = New Rectangle( _
            imageRect.Width, _
            MyBase.ContentRectangle.Top, _
            MyBase.ContentRectangle.Width - imageRect.Width, _
            MyBase.ContentRectangle.Height)
        ElseIf MyBase.TextImageRelation = _
        TextImageRelation.TextBeforeImage AndAlso _
        MyBase.TextDirection = ToolStripTextDirection.Horizontal Then
            imageRect = New Rectangle( _
            MyBase.ContentRectangle.Right - MyBase.Image.Width, _
            centerY, _
            MyBase.Image.Width, _
            MyBase.Image.Height)
            textRect = New Rectangle( _
            MyBase.ContentRectangle.Left, _
            MyBase.ContentRectangle.Top, _
            imageRect.X, _
            MyBase.ContentRectangle.Bottom)
        End If
    End Sub
End Class
' This is the custom renderer for the RolloverItem control.
' It draws a border around the item when the mouse is
' in the item's client area. It also draws the item's image
' in an inactive state (grayed out) until the user clicks
' the item to toggle its "clicked" state.
Friend Class RolloverItemRenderer
    Inherits ToolStripSystemRenderer
    Protected Overrides Sub OnRenderItemImage(ByVal e As ToolStripItemImageRenderEventArgs)
        MyBase.OnRenderItemImage(e)
        Dim item As RolloverItem = CType(e.Item, RolloverItem)
        ' If the ToolSTripItem is of type RolloverItem, 
        ' perform custom rendering for the image.
        If (item IsNot Nothing) Then
            If item.Clicked Then
                ' The item is in the clicked state, so 
                ' draw the image as usual.
                e.Graphics.DrawImage(e.Image, e.ImageRectangle.X, e.ImageRectangle.Y)
            Else
                ' In the unclicked state, gray out the image.
                ControlPaint.DrawImageDisabled(e.Graphics, e.Image, e.ImageRectangle.X, e.ImageRectangle.Y, item.BackColor)
            End If
        End If
    End Sub
    ' This method defines the behavior for rendering the
    ' background of a ToolStripItem. If the item is a
    ' RolloverItem, it paints the item's BackgroundImage 
    ' centered in the client area. If the mouse is in the 
    ' item's client area, a border is drawn around it.
    ' If the item is on a drop-down or if it is on the
    ' overflow, a gradient is painted in the background.
    Protected Overrides Sub OnRenderItemBackground(ByVal e As ToolStripItemRenderEventArgs)
        MyBase.OnRenderItemBackground(e)
        Dim item As RolloverItem = CType(e.Item, RolloverItem)
        ' If the ToolSTripItem is of type RolloverItem, 
        ' perform custom rendering for the background.
        If (item IsNot Nothing) Then
            If item.Placement = ToolStripItemPlacement.Overflow OrElse item.IsOnDropDown Then
                Dim b As New LinearGradientBrush(item.ContentRectangle, Color.Salmon, Color.DarkRed, 0.0F, False)
                Try
                    e.Graphics.FillRectangle(b, item.ContentRectangle)
                Finally
                    b.Dispose()
                End Try
            End If
            ' The RolloverItem control only supports 
            ' the ImageLayout.Center setting for the
            ' BackgroundImage property.
            If item.BackgroundImageLayout = ImageLayout.Center Then
                ' Get references to the item's ContentRectangle
                ' and BackgroundImage, for convenience.
                Dim cr As Rectangle = item.ContentRectangle
                Dim bgi As Image = item.BackgroundImage
                ' Compute the center of the item's ContentRectangle.
                Dim centerX As Integer = CInt((cr.Width - bgi.Width) / 2)
                Dim centerY As Integer = CInt((cr.Height - bgi.Height) / 2)
                ' If the item is selected, draw the background
                ' image as usual. Otherwise, draw it as disabled.
                If item.Selected Then
                    e.Graphics.DrawImage(bgi, centerX, centerY)
                Else
                    ControlPaint.DrawImageDisabled(e.Graphics, bgi, centerX, centerY, item.BackColor)
                End If
            End If
            ' If the item is in the rollover state, 
            ' draw a border around it.
            If item.Rollover Then
                ControlPaint.DrawFocusRectangle(e.Graphics, item.ContentRectangle)
            End If
        End If
    End Sub
End Class
' This form tests various features of the RolloverItem
' control. RolloverItem conrols are created and added
' to the form's ToolStrip. They are also created and 
' added to a button's ContextMenuStrip. The behavior
' of the RolloverItem control differs depending on 
' the type of parent control.
Public Class RolloverItemTestForm
   Inherits Form
   Private toolStrip1 As System.Windows.Forms.ToolStrip
   Private WithEvents button1 As System.Windows.Forms.Button
   
   Private infoIconKey As String = "Information icon"
   Private handIconKey As String = "Hand icon"
   Private exclIconKey As String = "Exclamation icon"
   Private questionIconKey As String = "Question icon"
   Private warningIconKey As String = "Warning icon "
   
   Private components As System.ComponentModel.IContainer = Nothing
   
   
   Public Sub New()
      InitializeComponent()
      
      ' Set up the form's ToolStrip control.
      InitializeToolStrip()
      
      ' Set up the ContextMenuStrip for the button.
      InitializeContextMenu()
    End Sub
   
   
   ' This utility method initializes the ToolStrip control's 
   ' image list. For convenience, icons from the SystemIcons 
   ' class are used for this demonstration, but any images
   ' could be used.
   Private Sub InitializeImageList(ts As ToolStrip)
      If ts.ImageList Is Nothing Then
         ts.ImageList = New ImageList()
         ts.ImageList.ImageSize = SystemIcons.Exclamation.Size
         
         ts.ImageList.Images.Add(Me.infoIconKey, SystemIcons.Information)
         
         ts.ImageList.Images.Add(Me.handIconKey, SystemIcons.Hand)
         
         ts.ImageList.Images.Add(Me.exclIconKey, SystemIcons.Exclamation)
         
         ts.ImageList.Images.Add(Me.questionIconKey, SystemIcons.Question)
         
         ts.ImageList.Images.Add(Me.warningIconKey, SystemIcons.Warning)
      End If
    End Sub
   
   
   Private Sub InitializeToolStrip()
      Me.InitializeImageList(Me.toolStrip1)
      
      Me.toolStrip1.Renderer = New RolloverItemRenderer()
      
      Dim item As RolloverItem = Me.CreateRolloverItem(Me.toolStrip1, "RolloverItem on ToolStrip", Me.Font, infoIconKey, TextImageRelation.ImageBeforeText, exclIconKey)
      
      Me.toolStrip1.Items.Add(item)
      
      item = Me.CreateRolloverItem(Me.toolStrip1, "RolloverItem on ToolStrip", Me.Font, infoIconKey, TextImageRelation.ImageBeforeText, exclIconKey)
      
      Me.toolStrip1.Items.Add(item)
    End Sub
   
   
   Private Sub InitializeContextMenu()
        Dim f As New System.Drawing.Font("Arial", 18.0F, FontStyle.Bold)
      
      Dim cms As New ContextMenuStrip()
      Me.InitializeImageList(cms)
      
      cms.Renderer = New RolloverItemRenderer()
      cms.AutoSize = True
      cms.ShowCheckMargin = False
      cms.ShowImageMargin = False
      
        Dim item As RolloverItem = Me.CreateRolloverItem( _
        cms, _
        "RolloverItem on ContextMenuStrip", _
        f, _
        handIconKey, _
        TextImageRelation.ImageBeforeText, _
        exclIconKey)
      
      cms.Items.Add(item)
      
        item = Me.CreateRolloverItem( _
        cms, _
        "Another RolloverItem on ContextMenuStrip", _
        f, _
        questionIconKey, _
        TextImageRelation.ImageBeforeText, _
        exclIconKey)
      
      cms.Items.Add(item)
      
        item = Me.CreateRolloverItem( _
        cms, _
        "And another RolloverItem on ContextMenuStrip", _
        CType(f, Drawing.Font), _
        warningIconKey, _
        TextImageRelation.ImageBeforeText, _
        exclIconKey)
      
      cms.Items.Add(item)
      
      AddHandler cms.Closing, AddressOf cms_Closing
      
      Me.button1.ContextMenuStrip = cms
    End Sub
   
   
   ' This method handles the ContextMenuStrip 
   ' control's Closing event. It prevents the 
   ' RolloverItem from closing the drop-down  
   ' when the item is clicked.
   Private Sub cms_Closing(sender As Object, e As ToolStripDropDownClosingEventArgs)
      If e.CloseReason = ToolStripDropDownCloseReason.ItemClicked Then
         e.Cancel = True
      End If
    End Sub
   
   
   ' This method handles the Click event for the button.
   ' it selects the first item in the ToolStrip control
   ' by using the ToolStripITem.Select method.
   Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
        Dim item As RolloverItem = CType(Me.toolStrip1.Items(0), RolloverItem)
      
      If (item IsNot Nothing) Then
         item.Select()
         
         Me.Invalidate()
      End If
    End Sub
   ' This utility method creates a RolloverItem 
   ' and adds it to a ToolStrip control.
    Private Function CreateRolloverItem( _
    ByVal owningToolStrip As ToolStrip, _
    ByVal txt As String, _
    ByVal f As Font, _
    ByVal imgKey As String, _
    ByVal tir As TextImageRelation, _
    ByVal backImgKey As String) As RolloverItem
        Dim item As New RolloverItem()
        item.Alignment = ToolStripItemAlignment.Left
        item.AllowDrop = False
        item.AutoSize = True
        item.BackgroundImage = owningToolStrip.ImageList.Images(backImgKey)
        item.BackgroundImageLayout = ImageLayout.Center
        item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
        item.DoubleClickEnabled = True
        item.Enabled = True
        item.Font = f
        ' These assignments are equivalent. Each assigns an
        ' image from the owning toolstrip's image list.
        item.ImageKey = imgKey
        'item.Image = owningToolStrip.ImageList.Images[infoIconKey];
        'item.ImageIndex = owningToolStrip.ImageList.Images.IndexOfKey(infoIconKey);
        item.ImageScaling = ToolStripItemImageScaling.None
        item.Owner = owningToolStrip
        item.Padding = New Padding(2)
        item.Text = txt
        item.TextAlign = ContentAlignment.MiddleLeft
        item.TextDirection = ToolStripTextDirection.Horizontal
        item.TextImageRelation = tir
        Return item
    End Function
   Protected Overrides Sub Dispose(disposing As Boolean)
      If disposing AndAlso (components IsNot Nothing) Then
         components.Dispose()
      End If
      MyBase.Dispose(disposing)
    End Sub
   
   #Region "Windows Form Designer generated code"
   
   Private Sub InitializeComponent()
      Me.toolStrip1 = New System.Windows.Forms.ToolStrip()
      Me.button1 = New System.Windows.Forms.Button()
      Me.SuspendLayout()
      ' 
      ' toolStrip1
      ' 
      Me.toolStrip1.AllowItemReorder = True
      Me.toolStrip1.Location = New System.Drawing.Point(0, 0)
      Me.toolStrip1.Name = "toolStrip1"
      Me.toolStrip1.Size = New System.Drawing.Size(845, 25)
      Me.toolStrip1.TabIndex = 0
      Me.toolStrip1.Text = "toolStrip1"
      ' 
      ' button1
      ' 
      Me.button1.Location = New System.Drawing.Point(12, 100)
      Me.button1.Name = "button1"
      Me.button1.Size = New System.Drawing.Size(86, 23)
      Me.button1.TabIndex = 1
      Me.button1.Text = "Click to select"
      Me.button1.UseVisualStyleBackColor = True
      ' 
      ' RolloverItemTestForm
      ' 
      Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 14F)
      Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
      Me.AutoSize = True
      Me.ClientSize = New System.Drawing.Size(845, 282)
      Me.Controls.Add(button1)
      Me.Controls.Add(toolStrip1)
        Me.Font = New System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0)
      Me.Name = "RolloverItemTestForm"
      Me.Text = "Form1"
      Me.ResumeLayout(False)
      Me.PerformLayout()
    End Sub
   
#End Region
End Class
Public Class Program
    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New RolloverItemTestForm())
    End Sub
End Class
注解
是ToolStripItem按钮、组合框、文本框或标签等元素,可以包含在控件或ToolStripDropDown控件中ToolStrip,这类似于 Windows 快捷菜单。 类 ToolStrip 管理这些元素的绘图和键盘和鼠标输入(包括拖放输入),类 ToolStripItem 管理元素本身的事件和布局。
ToolStripItem 类直接从 ToolStripItem 继承,或是通过 ToolStripControlHost 或 ToolStripDropDownItem 间接从 ToolStripItem 继承。
ToolStripItem 控件必须包含在 ToolStrip、MenuStrip、StatusStrip 或 ContextMenuStrip 中,不能直接添加到窗体中。 各种容器类设计为包含 ToolStripItem 控件的适当子集。
注意 给定 ToolStripItem 的 不能有多个父 ToolStrip。 必须复制 并将其 ToolStripItem 添加到其他 ToolStrip 控件。
下表显示了派生自 类的元素,ToolStripItem因此这些元素可以托管在 或 ToolStripDropDown中ToolStrip。
| 元素 | 说明 | 
|---|---|
| ToolStripButton | 支持图像和文本的工具栏按钮。 | 
| ToolStripLabel | 通常用于状态栏或作为批注或 ToolStrip 标题的文本标签。 | 
| ToolStripSeparator | 一个不可选择的空间或空间,带有垂直条,直观地对元素进行分组。 | 
| ToolStripControlHost | 承载 ToolStripItemToolStripComboBox、ToolStripTextBox、ToolStripProgressBar、其他Windows 窗体控件或自定义控件的 。 是 ToolStripComboBox 一个文本框,用户可以在其中输入文本,以及用户可以从中选择文本以填充文本框的列表。 ToolStripTextBox使用户能够输入文本。 表示 ToolStripProgressBar 包含在 中的 StatusStripWindows 进度栏控件。 | 
| ToolStripDropDownItem | 承载 ToolStripItemToolStripMenuItem、 ToolStripSplitButton和 ToolStripDropDownButton的 。 是 ToolStripMenuItem 显示在菜单或上下文菜单上的一个可选选项。 是 ToolStripSplitButton 常规按钮和下拉按钮的组合。 是 ToolStripDropDownButton 支持下拉功能的按钮。 | 
| ToolStripStatusLabel | 控件中的 StatusStrip 面板。 | 
构造函数
| ToolStripItem() | 初始化 ToolStripItem 类的新实例。 | 
| ToolStripItem(String, Image, EventHandler) | 使用指定的名称、图像和事件处理程序初始化 ToolStripItem 类的一个新实例。 | 
| ToolStripItem(String, Image, EventHandler, String) | 初始化 ToolStripItem 类的一个新实例,使其具有指定的显示文本、图像、事件处理程序和名称。 | 
属性
| AccessibilityObject | 获取分配给该控件的 AccessibleObject。 | 
| AccessibleDefaultActionDescription | 获取或设置控件的默认操作说明以供具有辅助功能的客户端应用程序使用。 | 
| AccessibleDescription | 获取或设置将报告给具有辅助功能的客户端应用程序的说明。 | 
| AccessibleName | 获取或设置供具有辅助功能的客户端应用程序使用的控件的名称。 | 
| AccessibleRole | 获取或设置控件的辅助性角色,该角色指定控件的用户界面元素的类型。 | 
| Alignment | 获取或设置一个值,该值指示该项是否与 ToolStrip 的起始或结尾处对齐。 | 
| AllowDrop | 获取或设置一个值,该值指示是否通过你实现的事件来处理拖放和项重新排序。 | 
| Anchor | 获取或设置 ToolStripItem 要绑定到的容器的边缘,并确定 ToolStripItem 如何随其父级调整大小。 | 
| AutoSize | 获取或设置一个值,该值指示是否自动调整项的大小。 | 
| AutoToolTip | 获取或设置一个值,该值指示对 ToolTipText 工具提示使用 Text 属性还是 ToolStripItem 属性。 | 
| Available | 获取或设置一个值,该值指示是否应该将 ToolStripItem 放置在 ToolStrip 上。 | 
| BackColor | 获取或设置项的背景色。 | 
| BackgroundImage | 获取或设置在项中显示的背景图像。 | 
| BackgroundImageLayout | 获取或设置用于 ToolStripItem 的背景图像布局。 | 
| BindingContext | 获取或设置 IBindableComponent 的货币管理器的集合。(继承自 BindableComponent) | 
| Bounds | 获取项的大小和位置。 | 
| CanRaiseEvents | 获取一个指示组件是否可以引发事件的值。(继承自 Component) | 
| CanSelect | 获取一个值,该值指示能否选择该项。 | 
| Command | 获取或设置调用 ICommand ToolStripItem 事件时将调用其 Execute(Object) 方法的 Click 。 | 
| CommandParameter | |
| Container | 获取包含 IContainer 的 Component。(继承自 Component) | 
| ContentRectangle | 获取在不覆盖背景边框的情况下,可以将内容(如文本和图标)放置在 ToolStripItem 内的哪个区域。 | 
| DataBindings | 获取此 IBindableComponent 的数据绑定对象的集合。(继承自 BindableComponent) | 
| DefaultAutoToolTip | 获取一个值,该值指示是否显示定义为默认值的 ToolTip。 | 
| DefaultDisplayStyle | 获取一个值,该值指示在 ToolStripItem 上显示的内容。 | 
| DefaultMargin | 获取项的默认边距。 | 
| DefaultPadding | 获取项的内部间距特征。 | 
| DefaultSize | 获取项的默认大小。 | 
| DesignMode | 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自 Component) | 
| DismissWhenClicked | 获取一个值,该值指示在单击 ToolStripDropDown 上的项后是否隐藏这些项。 | 
| DisplayStyle | 获取或设置是否在 ToolStripItem 上显示文本和图像。 | 
| Dock | 获取或设置要停靠在其父控件上的 ToolStripItem 边框,并确定 ToolStripItem 如何随其父控件一起调整大小。 | 
| DoubleClickEnabled | 获取或设置一个值,该值指示通过双击鼠标能否激活 ToolStripItem。 | 
| Enabled | 获取或设置一个值,该值指示是否启用了 ToolStripItem 的父控件。 | 
| Events | 获取附加到此 Component 的事件处理程序的列表。(继承自 Component) | 
| Font | 获取或设置由该项显示的文本的字体。 | 
| ForeColor | 获取或设置项的前景色。 | 
| Height | 获取或设置 ToolStripItem 的高度(以像素为单位)。 | 
| Image | 获取或设置显示在 ToolStripItem 上的图像。 | 
| ImageAlign | 获取或设置 ToolStripItem 上的图像对齐方式。 | 
| ImageIndex | 获取或设置在该项上显示的图像的索引值。 | 
| ImageKey | 获取或设置显示在 ImageList 上的 ToolStripItem 中图像的键访问器。 | 
| ImageScaling | 获取或设置一个值,该值指示是否根据容器自动调整 ToolStripItem 上图像的大小。 | 
| ImageTransparentColor | 获取或设置 ToolStripItem 图像中被视为透明的颜色。 | 
| IsDisposed | 获取一个值,该值指示对象是否已被释放。 | 
| IsOnDropDown | 获取一个值,该值指示当前 Control 的容器是否是 ToolStripDropDown。 | 
| IsOnOverflow | |
| Margin | 获取或设置项与相邻项之间的间距。 | 
| MergeAction | 获取或设置如何将子菜单与父菜单合并。 | 
| MergeIndex | 获取或设置合并的项在当前 ToolStrip 内的位置。 | 
| Name | 获取或设置项的名称。 | 
| Overflow | 获取或设置该项应附加到 ToolStrip 或 ToolStripOverflowButton,还是漂浮在两者之间。 | 
| Owner | 获取或设置此项的所有者。 | 
| OwnerItem | 获取此 ToolStripItem 的父级 ToolStripItem。 | 
| Padding | 获取或设置项的内容与其边缘之间的内部间距(以像素为单位)。 | 
| Parent | 获取或设置 ToolStripItem 的父容器。 | 
| Placement | 获取项的当前布局。 | 
| Pressed | 获取一个值,该值指示该项是否处于按下状态。 | 
| Renderer | 表示对 ToolStrip 或 ToolStripDropDown 可以包含的所有元素的事件和布局进行管理的抽象基类。 | 
| RightToLeft | 获取或设置一个值,该值指示项的放置顺序和文本的写入顺序是否均为从右向左。 | 
| RightToLeftAutoMirrorImage | 当 ToolStripItem 属性设置为 RightToLeft 时,将自动镜像 Yes 图像。 | 
| Selected | 获取一个值,该值指示该项是否处于选定状态。 | 
| ShowKeyboardCues | 获取一个值,该值指示是显示还是隐藏快捷键。 | 
| Site | (继承自 Component) | 
| Size | 获取或设置项的大小。 | 
| Tag | 获取或设置包含与项有关的数据的对象。 | 
| Text | 获取或设置要显示在项上的文本。 | 
| TextAlign | 获取或设置 ToolStripLabel 上的文本的对齐方式。 | 
| TextDirection | 获取 ToolStripItem 上所用文本的方向。 | 
| TextImageRelation | 获取或设置 ToolStripItem 文本和图像相对于彼此的位置。 | 
| ToolTipText | 获取或设置作为控件的 ToolTip 显示的文本。 | 
| Visible | 获取或设置一个值,该值指示是否显示该项。 | 
| Width | 获取或设置 ToolStripItem 的宽度(以像素为单位)。 | 
方法
事件
显式接口实现
| IDropTarget.OnDragDrop(DragEventArgs) | 引发 DragDrop 事件。 | 
| IDropTarget.OnDragEnter(DragEventArgs) | 引发 DragEnter 事件。 | 
| IDropTarget.OnDragLeave(EventArgs) | 引发 DragLeave 事件。 | 
| IDropTarget.OnDragOver(DragEventArgs) | 引发  |