ToolStripRenderer Clase

Definición

Controla la funcionalidad de dibujo de los objetos ToolStrip.

public ref class ToolStripRenderer abstract
public abstract class ToolStripRenderer
type ToolStripRenderer = class
Public MustInherit Class ToolStripRenderer
Herencia
ToolStripRenderer
Derivado

Ejemplos

En el ejemplo de código siguiente, se muestra cómo implementar una clase ToolStripRenderer personalizada. La GridStripRenderer clase personaliza tres aspectos de la GridStrip apariencia del control: GridStrip borde, ToolStripButton borde e ToolStripButton imagen. Para obtener una lista de código completa, consulte How to: Implement a Custom ToolStripRenderer.

// This class implements a custom ToolStripRenderer for the 
// GridStrip control. It customizes three aspects of the 
// GridStrip control's appearance: GridStrip border, 
// ToolStripButton border, and ToolStripButton image.
internal class GridStripRenderer : ToolStripRenderer
{   
    // The style of the empty cell's text.
    private static StringFormat style = new StringFormat();

    // The thickness (width or height) of a 
    // ToolStripButton control's border.
    static int borderThickness = 2;

    // The main bitmap that is the source for the 
    // subimagesthat are assigned to individual 
    // ToolStripButton controls.
    private Bitmap bmp = null;

    // The brush that paints the background of 
    // the GridStrip control.
    private Brush backgroundBrush = null;

    // This is the static constructor. It initializes the
    // StringFormat for drawing the text in the empty cell.
    static GridStripRenderer()
    {
        style.Alignment = StringAlignment.Center;
        style.LineAlignment = StringAlignment.Center;
    }

    // This method initializes the GridStripRenderer by
    // creating the image that is used as the source for
    // the individual button images.
    protected override void Initialize(ToolStrip ts)
    {
        base.Initialize(ts);

        this.InitializeBitmap(ts);
    }

    // This method initializes an individual ToolStripButton
    // control. It copies a subimage from the GridStripRenderer's
    // main image, according to the position and size of 
    // the ToolStripButton.
    protected override void InitializeItem(ToolStripItem item)
    {
        base.InitializeItem(item);

        GridStrip gs = item.Owner as GridStrip;

        // The empty cell does not receive a subimage.
        if ((item is ToolStripButton) &&
            (item != gs.EmptyCell))
        {
            // Copy the subimage from the appropriate 
            // part of the main image.
            Bitmap subImage = bmp.Clone(
                item.Bounds,
                PixelFormat.Undefined);

            // Assign the subimage to the ToolStripButton
            // control's Image property.
            item.Image = subImage;
        }
    }

    // This utility method creates the main image that
    // is the source for the subimages of the individual 
    // ToolStripButton controls.
    private void InitializeBitmap(ToolStrip toolStrip)
    {
        // Create the main bitmap, into which the image is drawn.
        this.bmp = new Bitmap(
            toolStrip.Size.Width,
            toolStrip.Size.Height);

        // Draw a fancy pattern. This could be any image or drawing.
        using (Graphics g = Graphics.FromImage(bmp))
        {
            // Draw smoothed lines.
            g.SmoothingMode = SmoothingMode.AntiAlias;
            
            // Draw the image. In this case, it is 
            // a number of concentric ellipses. 
            for (int i = 0; i < toolStrip.Size.Width; i += 8)
            {
                g.DrawEllipse(Pens.Blue, 0, 0, i, i);
            }
        }
    }

    // This method draws a border around the GridStrip control.
    protected override void OnRenderToolStripBorder(
        ToolStripRenderEventArgs e)
    {
        base.OnRenderToolStripBorder(e);

        ControlPaint.DrawFocusRectangle(
            e.Graphics,
            e.AffectedBounds,
            SystemColors.ControlDarkDark,
            SystemColors.ControlDarkDark);
    }

    // This method renders the GridStrip control's background.
    protected override void OnRenderToolStripBackground(
        ToolStripRenderEventArgs e)
    {
        base.OnRenderToolStripBackground(e);

        // This late initialization is a workaround. The gradient
        // depends on the bounds of the GridStrip control. The bounds 
        // are dependent on the layout engine, which hasn't fully
        // performed layout by the time the Initialize method runs.
        if (this.backgroundBrush == null)
        {
            this.backgroundBrush = new LinearGradientBrush(
               e.ToolStrip.ClientRectangle,
               SystemColors.ControlLightLight,
               SystemColors.ControlDark,
               90,
               true);
        }

        // Paint the GridStrip control's background.
        e.Graphics.FillRectangle(
            this.backgroundBrush, 
            e.AffectedBounds);
    }

    // This method draws a border around the button's image. If the background
    // to be rendered belongs to the empty cell, a string is drawn. Otherwise,
    // a border is drawn at the edges of the button.
    protected override void OnRenderButtonBackground(
        ToolStripItemRenderEventArgs e)
    {
        base.OnRenderButtonBackground(e);

        // Define some local variables for convenience.
        Graphics g = e.Graphics;
        GridStrip gs = e.ToolStrip as GridStrip;
        ToolStripButton gsb = e.Item as ToolStripButton;

        // Calculate the rectangle around which the border is painted.
        Rectangle imageRectangle = new Rectangle(
            borderThickness, 
            borderThickness, 
            e.Item.Width - 2 * borderThickness, 
            e.Item.Height - 2 * borderThickness);

        // If rendering the empty cell background, draw an 
        // explanatory string, centered in the ToolStripButton.
        if (gsb == gs.EmptyCell)
        {
            e.Graphics.DrawString(
                "Drag to here",
                gsb.Font, 
                SystemBrushes.ControlDarkDark,
                imageRectangle, style);
        }
        else
        {
            // If the button can be a drag source, paint its border red.
            // otherwise, paint its border a dark color.
            Brush b = gs.IsValidDragSource(gsb) ? b = 
                Brushes.Red : SystemBrushes.ControlDarkDark;

            // Draw the top segment of the border.
            Rectangle borderSegment = new Rectangle(
                0, 
                0, 
                e.Item.Width, 
                imageRectangle.Top);
            g.FillRectangle(b, borderSegment);

            // Draw the right segment.
            borderSegment = new Rectangle(
                imageRectangle.Right,
                0,
                e.Item.Bounds.Right - imageRectangle.Right,
                imageRectangle.Bottom);
            g.FillRectangle(b, borderSegment);

            // Draw the left segment.
            borderSegment = new Rectangle(
                0,
                0,
                imageRectangle.Left,
                e.Item.Height);
            g.FillRectangle(b, borderSegment);

            // Draw the bottom segment.
            borderSegment = new Rectangle(
                0,
                imageRectangle.Bottom,
                e.Item.Width,
                e.Item.Bounds.Bottom - imageRectangle.Bottom);
            g.FillRectangle(b, borderSegment);
        }
    }
}
' This class implements a custom ToolStripRenderer for the 
' GridStrip control. It customizes three aspects of the 
' GridStrip control's appearance: GridStrip border, 
' ToolStripButton border, and ToolStripButton image.
Friend Class GridStripRenderer
     Inherits ToolStripRenderer

   ' The style of the empty cell's text.
   Private Shared style As New StringFormat()
   
   ' The thickness (width or height) of a 
   ' ToolStripButton control's border.
   Private Shared borderThickness As Integer = 2
   
   ' The main bitmap that is the source for the 
   ' subimagesthat are assigned to individual 
   ' ToolStripButton controls.
   Private bmp As Bitmap = Nothing
   
   ' The brush that paints the background of 
   ' the GridStrip control.
   Private backgroundBrush As Brush = Nothing
   
   
   ' This is the static constructor. It initializes the
   ' StringFormat for drawing the text in the empty cell.
   Shared Sub New()
      style.Alignment = StringAlignment.Center
      style.LineAlignment = StringAlignment.Center
   End Sub 
   
   ' This method initializes the GridStripRenderer by
   ' creating the image that is used as the source for
   ' the individual button images.
   Protected Overrides Sub Initialize(ts As ToolStrip)
      MyBase.Initialize(ts)
      
      Me.InitializeBitmap(ts)
     End Sub

   ' This method initializes an individual ToolStripButton
   ' control. It copies a subimage from the GridStripRenderer's
   ' main image, according to the position and size of 
   ' the ToolStripButton.
   Protected Overrides Sub InitializeItem(item As ToolStripItem)
      MyBase.InitializeItem(item)
      
         Dim gs As GridStrip = item.Owner
      
      ' The empty cell does not receive a subimage.
         If ((TypeOf (item) Is ToolStripButton) And _
              (item IsNot gs.EmptyCell)) Then
             ' Copy the subimage from the appropriate 
             ' part of the main image.
             Dim subImage As Bitmap = bmp.Clone(item.Bounds, PixelFormat.Undefined)

             ' Assign the subimage to the ToolStripButton
             ' control's Image property.
             item.Image = subImage
         End If
   End Sub 

   ' This utility method creates the main image that
   ' is the source for the subimages of the individual 
   ' ToolStripButton controls.
   Private Sub InitializeBitmap(toolStrip As ToolStrip)
      ' Create the main bitmap, into which the image is drawn.
      Me.bmp = New Bitmap(toolStrip.Size.Width, toolStrip.Size.Height)
      
      ' Draw a fancy pattern. This could be any image or drawing.
      Dim g As Graphics = Graphics.FromImage(bmp)
      Try
         ' Draw smoothed lines.
         g.SmoothingMode = SmoothingMode.AntiAlias
         
         ' Draw the image. In this case, it is 
         ' a number of concentric ellipses. 
         Dim i As Integer
         For i = 0 To toolStrip.Size.Width - 8 Step 8
            g.DrawEllipse(Pens.Blue, 0, 0, i, i)
         Next i
      Finally
         g.Dispose()
      End Try
   End Sub 
   
   ' This method draws a border around the GridStrip control.
   Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs)
      MyBase.OnRenderToolStripBorder(e)
      
      ControlPaint.DrawFocusRectangle(e.Graphics, e.AffectedBounds, SystemColors.ControlDarkDark, SystemColors.ControlDarkDark)
   End Sub 

   ' This method renders the GridStrip control's background.
   Protected Overrides Sub OnRenderToolStripBackground(e As ToolStripRenderEventArgs)
      MyBase.OnRenderToolStripBackground(e)
      
      ' This late initialization is a workaround. The gradient
      ' depends on the bounds of the GridStrip control. The bounds 
      ' are dependent on the layout engine, which hasn't fully
      ' performed layout by the time the Initialize method runs.
      If Me.backgroundBrush Is Nothing Then
         Me.backgroundBrush = New LinearGradientBrush(e.ToolStrip.ClientRectangle, SystemColors.ControlLightLight, SystemColors.ControlDark, 90, True)
      End If
      
      ' Paint the GridStrip control's background.
      e.Graphics.FillRectangle(Me.backgroundBrush, e.AffectedBounds)
     End Sub

   ' This method draws a border around the button's image. If the background
   ' to be rendered belongs to the empty cell, a string is drawn. Otherwise,
   ' a border is drawn at the edges of the button.
   Protected Overrides Sub OnRenderButtonBackground(e As ToolStripItemRenderEventArgs)
      MyBase.OnRenderButtonBackground(e)
      
      ' Define some local variables for convenience.
      Dim g As Graphics = e.Graphics
      Dim gs As GridStrip = e.ToolStrip 
      Dim gsb As ToolStripButton = e.Item 
      
      ' Calculate the rectangle around which the border is painted.
      Dim imageRectangle As New Rectangle(borderThickness, borderThickness, e.Item.Width - 2 * borderThickness, e.Item.Height - 2 * borderThickness)
      
      ' If rendering the empty cell background, draw an 
      ' explanatory string, centered in the ToolStripButton.
         If gsb Is gs.EmptyCell Then
             e.Graphics.DrawString("Drag to here", gsb.Font, SystemBrushes.ControlDarkDark, imageRectangle, style)
         Else
             ' If the button can be a drag source, paint its border red.
             ' otherwise, paint its border a dark color.
             Dim b As Brush = IIf(gs.IsValidDragSource(gsb), Brushes.Red, SystemBrushes.ControlDarkDark)

             ' Draw the top segment of the border.
             Dim borderSegment As New Rectangle(0, 0, e.Item.Width, imageRectangle.Top)
             g.FillRectangle(b, borderSegment)

             ' Draw the right segment.
             borderSegment = New Rectangle(imageRectangle.Right, 0, e.Item.Bounds.Right - imageRectangle.Right, imageRectangle.Bottom)
             g.FillRectangle(b, borderSegment)

             ' Draw the left segment.
             borderSegment = New Rectangle(0, 0, imageRectangle.Left, e.Item.Height)
             g.FillRectangle(b, borderSegment)

             ' Draw the bottom segment.
             borderSegment = New Rectangle(0, imageRectangle.Bottom, e.Item.Width, e.Item.Bounds.Bottom - imageRectangle.Bottom)
             g.FillRectangle(b, borderSegment)
         End If
     End Sub
 End Class

Comentarios

Use la ToolStripRenderer clase para aplicar un estilo o tema determinado a .ToolStrip En lugar de pintar personalizado y ToolStrip los ToolStripItem objetos que contiene, establece la ToolStrip.Renderer propiedad en un objeto que hereda de ToolStripRenderer. La pintura especificada por ToolStripRenderer se aplica a , ToolStripasí como a los elementos que contiene.

Hay varias formas de realizar representaciones personalizadas en controles ToolStrip. Como sucede con otros controles de Windows Forms, tanto ToolStrip como ToolStripItem tienen métodos OnPaint y eventos Paint que se pueden invalidar. Al igual que con la representación al uso, el sistema de coordenadas es relativo al área cliente del control; es decir, la esquina superior izquierda del control es 0, 0. El evento Paint y el método OnPaint de un elemento ToolStripItem se comportan como otros eventos de representación de controles.

La ToolStripRenderer clase tiene métodos reemplazables para pintar el fondo, el fondo del elemento, la imagen del elemento, la flecha del elemento, el texto del elemento y el ToolStripborde de . Los argumentos de evento de estos métodos exponen varias propiedades, como rectángulos, colores y formatos de texto, que se pueden ajustar según sea necesario.

Para ajustar solo algunos aspectos de cómo se representa un elemento, normalmente lo que se hace es invalidar ToolStripRenderer.

Si va a escribir un elemento nuevo y desea controlar todos los aspectos de representación, invalide el método OnPaint. En OnPaint se pueden usar métodos de ToolStripRenderer.

ToolStrip se almacena doblemente en búfer de forma predeterminada, con lo cual se saca partido de la configuración OptimizedDoubleBuffer.

Constructores

ToolStripRenderer()

Inicializa una nueva instancia de la clase ToolStripRenderer.

Campos

Offset2X

Obtiene o establece el multiplicador de desplazamiento en dos veces el desplazamiento a lo largo del eje X.

Offset2Y

Obtiene o establece el multiplicador de desplazamiento en dos veces el desplazamiento a lo largo del eje Y.

Métodos

CreateDisabledImage(Image)

Crea una copia en escala de grises de una imagen determinada.

DrawArrow(ToolStripArrowRenderEventArgs)

Dibuja una flecha en un objeto ToolStripItem.

DrawButtonBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un objeto ToolStripButton.

DrawDropDownButtonBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un objeto ToolStripDropDownButton.

DrawGrip(ToolStripGripRenderEventArgs)

Dibuja un controlador de movimiento en un objeto ToolStrip.

DrawImageMargin(ToolStripRenderEventArgs)

Dibuja el espacio que rodea una imagen en un objeto ToolStrip.

DrawItemBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un objeto ToolStripItem.

DrawItemCheck(ToolStripItemImageRenderEventArgs)

Dibuja una imagen en un objeto ToolStripItem que indica que el elemento se encuentra en un estado seleccionado.

DrawItemImage(ToolStripItemImageRenderEventArgs)

Dibuja una imagen en un objeto ToolStripItem.

DrawItemText(ToolStripItemTextRenderEventArgs)

Dibuja texto en un objeto ToolStripItem.

DrawLabelBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un objeto ToolStripLabel.

DrawMenuItemBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un objeto ToolStripMenuItem.

DrawOverflowButtonBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo de un botón de desbordamiento.

DrawSeparator(ToolStripSeparatorRenderEventArgs)

Dibuja un ToolStripSeparator.

DrawSplitButton(ToolStripItemRenderEventArgs)

Dibuja un ToolStripSplitButton.

DrawStatusStripSizingGrip(ToolStripRenderEventArgs)

Dibuja un control de tamaño.

DrawToolStripBackground(ToolStripRenderEventArgs)

Dibuja el fondo de un objeto ToolStrip.

DrawToolStripBorder(ToolStripRenderEventArgs)

Dibuja el borde de un objeto ToolStrip.

DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs)

Dibuja el fondo del objeto ToolStripContentPanel.

DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs)

Dibuja el fondo del objeto ToolStripPanel.

DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs)

Dibuja el fondo del objeto ToolStripStatusLabel.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
Initialize(ToolStrip)

Cuando se reemplaza en una clase derivada, proporciona una inicialización personalizada del objeto ToolStrip especificado.

InitializeContentPanel(ToolStripContentPanel)

Inicializa el objeto ToolStripContentPanel especificado.

InitializeItem(ToolStripItem)

Cuando se reemplaza en una clase derivada, proporciona una inicialización personalizada del objeto ToolStripItem especificado.

InitializePanel(ToolStripPanel)

Inicializa el objeto ToolStripPanel especificado.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnRenderArrow(ToolStripArrowRenderEventArgs)

Genera el evento RenderArrow.

OnRenderButtonBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderButtonBackground.

OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderDropDownButtonBackground.

OnRenderGrip(ToolStripGripRenderEventArgs)

Genera el evento RenderGrip.

OnRenderImageMargin(ToolStripRenderEventArgs)

Dibuja el fondo del elemento.

OnRenderItemBackground(ToolStripItemRenderEventArgs)

Genera el evento OnRenderItemBackground(ToolStripItemRenderEventArgs).

OnRenderItemCheck(ToolStripItemImageRenderEventArgs)

Genera el evento RenderItemCheck.

OnRenderItemImage(ToolStripItemImageRenderEventArgs)

Genera el evento RenderItemImage.

OnRenderItemText(ToolStripItemTextRenderEventArgs)

Genera el evento RenderItemText.

OnRenderLabelBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderLabelBackground.

OnRenderMenuItemBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderMenuItemBackground.

OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderOverflowButtonBackground.

OnRenderSeparator(ToolStripSeparatorRenderEventArgs)

Genera el evento RenderSeparator.

OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs)

Genera el evento OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs).

OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs)

Genera el evento RenderStatusStripSizingGrip.

OnRenderToolStripBackground(ToolStripRenderEventArgs)

Genera el evento RenderToolStripBackground.

OnRenderToolStripBorder(ToolStripRenderEventArgs)

Genera el evento RenderToolStripBorder.

OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs)

Genera el evento RenderToolStripContentPanelBackground.

OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs)

Genera el evento RenderToolStripPanelBackground.

OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs)

Genera el evento RenderToolStripStatusLabelBackground.

ScaleArrowOffsetsIfNeeded()

Si es necesario aplicar escalado de acuerdo con la configuración de PPP del equipo, aplica los valores Offset2X y Offset2Y para escalar el icono de flecha.

ScaleArrowOffsetsIfNeeded(Int32)

Aplica los elementos Offset2X y Offset2Y para escalar el icono de flecha de acuerdo con el valor de PPP seleccionado.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Eventos

RenderArrow

Se desencadena cuando se procesa una flecha en un objeto ToolStripItem.

RenderButtonBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripButton.

RenderDropDownButtonBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripDropDownButton.

RenderGrip

Se desencadena cuando se procesa el controlador de movimiento de un objeto ToolStrip.

RenderImageMargin

Dibuja el margen comprendido entre una imagen y su contenedor.

RenderItemBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripItem.

RenderItemCheck

Se desencadena cuando se procesa la imagen de un objeto ToolStripItem seleccionado.

RenderItemImage

Se desencadena cuando se procesa la imagen de un objeto ToolStripItem.

RenderItemText

Se desencadena cuando se procesa el texto de un objeto ToolStripItem.

RenderLabelBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripLabel.

RenderMenuItemBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripMenuItem.

RenderOverflowButtonBackground

Se produce cuando se presenta el fondo de un botón de desbordamiento.

RenderSeparator

Se desencadena cuando se procesa un objeto ToolStripSeparator.

RenderSplitButtonBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStripSplitButton.

RenderStatusStripSizingGrip

Se produce cuando cambia el estilo de presentación.

RenderToolStripBackground

Se desencadena cuando se procesa el fondo de un objeto ToolStrip.

RenderToolStripBorder

Se desencadena cuando se procesa el borde de un objeto ToolStrip.

RenderToolStripContentPanelBackground

Dibuja el fondo de un objeto ToolStripContentPanel.

RenderToolStripPanelBackground

Dibuja el fondo de un objeto ToolStripPanel.

RenderToolStripStatusLabelBackground

Dibuja el fondo de un objeto ToolStripStatusLabel.

Se aplica a

Consulte también