Export (0) Print
Expand All

ToolStripItem Class

Represents the abstract base class that manages events and layout for all the elements that a ToolStrip or ToolStripDropDown can contain.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

'Declaration
Public MustInherit Class ToolStripItem _
	Inherits Component _
	Implements IDropTarget, IComponent, IDisposable

The ToolStripItem type exposes the following members.

  NameDescription
Protected methodToolStripItemInitializes a new instance of the ToolStripItem class.
Protected methodToolStripItem(String, Image, EventHandler)Initializes a new instance of the ToolStripItem class with the specified name, image, and event handler.
Protected methodToolStripItem(String, Image, EventHandler, String)Initializes a new instance of the ToolStripItem class with the specified display text, image, event handler, and name.
Top

  NameDescription
Public propertyAccessibilityObjectGets the AccessibleObject assigned to the control.
Public propertyAccessibleDefaultActionDescriptionGets or sets the default action description of the control for use by accessibility client applications.
Public propertyAccessibleDescriptionGets or sets the description that will be reported to accessibility client applications.
Public propertyAccessibleNameGets or sets the name of the control for use by accessibility client applications.
Public propertyAccessibleRoleGets or sets the accessible role of the control, which specifies the type of user interface element of the control.
Public propertyAlignmentGets or sets a value indicating whether the item aligns towards the beginning or end of the ToolStrip.
Public propertyAllowDropGets or sets a value indicating whether drag-and-drop and item reordering are handled through events that you implement.
Public propertyAnchorGets or sets the edges of the container to which a ToolStripItem is bound and determines how a ToolStripItem is resized with its parent.
Public propertyAutoSizeGets or sets a value indicating whether the item is automatically sized.
Public propertyAutoToolTipGets or sets a value indicating whether to use the Text property or the ToolTipText property for the ToolStripItem ToolTip.
Public propertyAvailableGets or sets a value indicating whether the ToolStripItem should be placed on a ToolStrip.
Public propertyBackColorGets or sets the background color for the item.
Public propertyBackgroundImageGets or sets the background image displayed in the item.
Public propertyBackgroundImageLayoutGets or sets the background image layout used for the ToolStripItem.
Public propertyBoundsGets the size and location of the item.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyCanSelectGets a value indicating whether the item can be selected.
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyContentRectangleGets the area where content, such as text and icons, can be placed within a ToolStripItem without overwriting background borders.
Protected propertyDefaultAutoToolTipGets a value indicating whether to display the ToolTip that is defined as the default.
Protected propertyDefaultDisplayStyleGets a value indicating what is displayed on the ToolStripItem.
Protected propertyDefaultMarginGets the default margin of an item.
Protected propertyDefaultPaddingGets the internal spacing characteristics of the item.
Protected propertyDefaultSizeGets the default size of the item.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyDismissWhenClickedGets a value indicating whether items on a ToolStripDropDown are hidden after they are clicked.
Public propertyDisplayStyleGets or sets whether text and images are displayed on a ToolStripItem.
Public propertyDockGets or sets which ToolStripItem borders are docked to its parent control and determines how a ToolStripItem is resized with its parent.
Public propertyDoubleClickEnabledGets or sets a value indicating whether the ToolStripItem can be activated by double-clicking the mouse.
Public propertyEnabledGets or sets a value indicating whether the parent control of the ToolStripItem is enabled.
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyFontGets or sets the font of the text displayed by the item.
Public propertyForeColorGets or sets the foreground color of the item.
Public propertyHeightGets or sets the height, in pixels, of a ToolStripItem.
Public propertyImageGets or sets the image that is displayed on a ToolStripItem.
Public propertyImageAlignGets or sets the alignment of the image on a ToolStripItem.
Public propertyImageIndexGets or sets the index value of the image that is displayed on the item.
Public propertyImageKeyGets or sets the key accessor for the image in the ImageList that is displayed on a ToolStripItem.
Public propertyImageScalingGets or sets a value indicating whether an image on a ToolStripItem is automatically resized to fit in a container.
Public propertyImageTransparentColorGets or sets the color to treat as transparent in a ToolStripItem image.
Public propertyIsDisposedGets a value indicating whether the object has been disposed of.
Public propertyIsOnDropDownGets a value indicating whether the container of the current Control is a ToolStripDropDown.
Public propertyIsOnOverflowGets a value indicating whether the Placement property is set to Overflow.
Public propertyMarginGets or sets the space between the item and adjacent items.
Public propertyMergeActionGets or sets how child menus are merged with parent menus.
Public propertyMergeIndexGets or sets the position of a merged item within the current ToolStrip.
Public propertyNameGets or sets the name of the item.
Public propertyOverflowGets or sets whether the item is attached to the ToolStrip or ToolStripOverflowButton or can float between the two.
Public propertyOwnerGets or sets the owner of this item.
Public propertyOwnerItemGets the parent ToolStripItem of this ToolStripItem.
Public propertyPaddingGets or sets the internal spacing, in pixels, between the item's contents and its edges.
Protected propertyParentGets or sets the parent container of the ToolStripItem.
Public propertyPlacementGets the current layout of the item.
Public propertyPressedGets a value indicating whether the state of the item is pressed.
Public propertyRightToLeftGets or sets a value indicating whether items are to be placed from right to left and text is to be written from right to left.
Public propertyRightToLeftAutoMirrorImageMirrors automatically the ToolStripItem image when the RightToLeft property is set to Yes.
Public propertySelectedGets a value indicating whether the item is selected.
Protected propertyShowKeyboardCuesGets a value indicating whether to show or hide shortcut keys.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Public propertySizeGets or sets the size of the item.
Public propertyTagGets or sets the object that contains data about the item.
Public propertyTextGets or sets the text that is to be displayed on the item.
Public propertyTextAlignGets or sets the alignment of the text on a ToolStripLabel.
Public propertyTextDirectionGets the orientation of text used on a ToolStripItem.
Public propertyTextImageRelationGets or sets the position of ToolStripItem text and image relative to each other.
Public propertyToolTipTextGets or sets the text that appears as a ToolTip for a control.
Public propertyVisibleGets or sets a value indicating whether the item is displayed.
Public propertyWidthGets or sets the width in pixels of a ToolStripItem.
Top

  NameDescription
Protected methodCreateAccessibilityInstanceCreates a new accessibility object for the ToolStripItem.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDisposeReleases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the ToolStripItem and optionally releases the managed resources. (Overrides Component.Dispose(Boolean).)
Public methodDoDragDropBegins a drag-and-drop operation.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGetCurrentParentRetrieves the ToolStrip that is the container of the current ToolStripItem.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodGetPreferredSizeRetrieves the size of a rectangular area into which a control can be fit.
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodInvalidateInvalidates the entire surface of the ToolStripItem and causes it to be redrawn.
Public methodInvalidate(Rectangle)Invalidates the specified region of the ToolStripItem by adding it to the update region of the ToolStripItem, which is the area that will be repainted at the next paint operation, and causes a paint message to be sent to the ToolStripItem.
Protected methodIsInputCharDetermines whether a character is an input character that the item recognizes.
Protected methodIsInputKeyDetermines whether the specified key is a regular input key or a special key that requires preprocessing.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodOnAvailableChangedRaises the AvailableChanged event.
Protected methodOnBackColorChangedRaises the BackColorChanged event.
Protected methodOnBoundsChangedOccurs when the Bounds property changes.
Protected methodOnClickRaises the Click event.
Protected methodOnDisplayStyleChangedRaises the DisplayStyleChanged event.
Protected methodOnDoubleClickRaises the DoubleClick event.
Protected methodOnDragDropRaises the DragDrop event.
Protected methodOnDragEnterRaises the DragEnter event.
Protected methodOnDragLeaveRaises the DragLeave event.
Protected methodOnDragOverRaises the DragOver event.
Protected methodOnEnabledChangedRaises the EnabledChanged event.
Protected methodOnFontChangedRaises the FontChanged event.
Protected methodOnForeColorChangedRaises the ForeColorChanged event.
Protected methodOnGiveFeedbackRaises the GiveFeedback event.
Protected methodOnLayoutRaises the Layout event.
Protected methodOnLocationChangedRaises the LocationChanged event.
Protected methodOnMouseDownRaises the MouseDown event.
Protected methodOnMouseEnterRaises the MouseEnter event.
Protected methodOnMouseHoverRaises the MouseHover event.
Protected methodOnMouseLeaveRaises the MouseLeave event.
Protected methodOnMouseMoveRaises the MouseMove event.
Protected methodOnMouseUpRaises the MouseUp event.
Protected methodOnOwnerChangedRaises the OwnerChanged event.
Protected methodOnOwnerFontChangedRaises the FontChanged event when the Font property has changed on the parent of the ToolStripItem.
Protected methodOnPaintRaises the Paint event.
Protected methodOnParentBackColorChangedRaises the BackColorChanged event.
Protected methodOnParentChangedRaises the ParentChanged event.
Protected methodOnParentEnabledChangedRaises the EnabledChanged event when the Enabled property value of the item's container changes.
Protected methodOnParentForeColorChangedRaises the ForeColorChanged event.
Protected methodOnParentRightToLeftChangedRaises the RightToLeftChanged event.
Protected methodOnQueryContinueDragRaises the QueryContinueDrag event.
Protected methodOnRightToLeftChangedRaises the RightToLeftChanged event.
Protected methodOnTextChangedRaises the TextChanged event.
Protected methodOnVisibleChangedRaises the VisibleChanged event.
Public methodPerformClickActivates the ToolStripItem when it is clicked with the mouse.
Protected methodProcessCmdKeyProcesses a command key.
Protected methodProcessDialogKeyProcesses a dialog key.
Protected methodProcessMnemonicProcesses a mnemonic character.
Public methodResetBackColorInfrastructure. This method is not relevant to this class.
Public methodResetDisplayStyleInfrastructure. This method is not relevant to this class.
Public methodResetFontInfrastructure. This method is not relevant to this class.
Public methodResetForeColorInfrastructure. This method is not relevant to this class.
Public methodResetImageInfrastructure. This method is not relevant to this class.
Public methodResetMarginInfrastructure. This method is not relevant to this class.
Public methodResetPaddingInfrastructure. This method is not relevant to this class.
Public methodResetRightToLeftInfrastructure. This method is not relevant to this class.
Public methodResetTextDirectionInfrastructure. This method is not relevant to this class.
Public methodSelectSelects the item.
Protected methodSetBoundsSets the size and location of the item.
Protected methodSetVisibleCoreSets the ToolStripItem to the specified visible state.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Overrides Component.ToString.)
Top

  NameDescription
Public eventAvailableChangedOccurs when the value of the Available property changes.
Public eventBackColorChangedOccurs when the value of the BackColor property changes.
Public eventClickOccurs when the ToolStripItem is clicked.
Public eventDisplayStyleChangedOccurs when the DisplayStyle has changed.
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventDoubleClickOccurs when the item is double-clicked with the mouse.
Public eventDragDropOccurs when the user drags an item and the user releases the mouse button, indicating that the item should be dropped into this item.
Public eventDragEnterOccurs when the user drags an item into the client area of this item.
Public eventDragLeaveOccurs when the user drags an item and the mouse pointer is no longer over the client area of this item.
Public eventDragOverOccurs when the user drags an item over the client area of this item.
Public eventEnabledChangedOccurs when the Enabled property value has changed.
Public eventForeColorChangedOccurs when the ForeColor property value changes.
Public eventGiveFeedbackOccurs during a drag operation.
Public eventLocationChangedOccurs when the location of a ToolStripItem is updated.
Public eventMouseDownOccurs when the mouse pointer is over the item and a mouse button is pressed.
Public eventMouseEnterOccurs when the mouse pointer enters the item.
Public eventMouseHoverOccurs when the mouse pointer hovers over the item.
Public eventMouseLeaveOccurs when the mouse pointer leaves the item.
Public eventMouseMoveOccurs when the mouse pointer is moved over the item.
Public eventMouseUpOccurs when the mouse pointer is over the item and a mouse button is released.
Public eventOwnerChangedOccurs when the Owner property changes.
Public eventPaintOccurs when the item is redrawn.
Public eventQueryAccessibilityHelpOccurs when an accessibility client application invokes help for the ToolStripItem.
Public eventQueryContinueDragOccurs during a drag-and-drop operation and allows the drag source to determine whether the drag-and-drop operation should be canceled.
Public eventRightToLeftChangedOccurs when the RightToLeft property value changes.
Public eventTextChangedOccurs when the value of the Text property changes.
Public eventVisibleChangedOccurs when the value of the Visible property changes.
Top

A ToolStripItem is an element such as a button, combo box, text box, or label that can be contained in a ToolStrip control or a ToolStripDropDown control, which is similar to a Windows shortcut menu. The ToolStrip class manages the painting and keyboard and mouse input, including drag-and-drop input, for these elements, and the ToolStripItem class manages events and layout within the elements themselves.

ToolStripItem classes either inherit directly from ToolStripItem, or they inherit indirectly from ToolStripItem through ToolStripControlHost or ToolStripDropDownItem.

ToolStripItem controls must be contained in a ToolStrip, MenuStrip, StatusStrip, or ContextMenuStrip and cannot be added directly to a form. The various container classes are designed to contain an appropriate subset of ToolStripItem controls.

Note   A given ToolStripItem cannot have more than one parent ToolStrip. You must copy of the ToolStripItem and add it to other ToolStrip controls.

The following table shows the elements that derive from the ToolStripItem class and which therefore can be hosted in a ToolStrip or ToolStripDropDown.

Element

Description

ToolStripButton

A toolbar button that supports images and text.

ToolStripLabel

A text label typically used in a status bar or ToolStrip as a comment or title.

ToolStripSeparator

A non-selectable space or space with a vertical bar that visually groups elements.

ToolStripControlHost

A ToolStripItem that hosts a ToolStripComboBox, ToolStripTextBox, ToolStripProgressBar, other Windows Forms controls, or custom controls.

A ToolStripComboBox is a text box in which the user can enter text, along with a list from which the user can select text to fill the text box.

A ToolStripTextBox enables the user to enter text.

A ToolStripProgressBar represents a Windows progress bar control contained in a StatusStrip.

ToolStripDropDownItem

A ToolStripItem that hosts a ToolStripMenuItem, ToolStripSplitButton, and ToolStripDropDownButton.

A ToolStripMenuItem is a selectable option displayed on a menu or context menu.

A ToolStripSplitButton is a combination of a regular button and a drop-down button.

A ToolStripDropDownButton is a button that supports drop-down functionality.

ToolStripStatusLabel

A panel in a StatusStrip control.

The following code example demonstrates how to implement a custom ToolStripItem control.

Option Strict On 
Option Explicit On 

Imports System
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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft