ToolStripRenderer Classe

Definição

Trata da funcionalidade de pintura dos ToolStrip objetos.

public ref class ToolStripRenderer abstract
public abstract class ToolStripRenderer
type ToolStripRenderer = class
Public MustInherit Class ToolStripRenderer
Herança
ToolStripRenderer
Derivado

Exemplos

O exemplo de código seguinte demonstra como implementar uma classe personalizada ToolStripRenderer . A GridStripRenderer classe personaliza três aspetos da GridStrip aparência do controlo: GridStrip borda, ToolStripButton borda e ToolStripButton imagem. Para uma lista completa de código, veja Como: Implementar um ToolStripRenderer Personalizado.

// 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

Observações

Use a ToolStripRenderer classe para aplicar um estilo ou tema particular a um ToolStrip. Em vez de pintar personalizadamente a ToolStrip e os ToolStripItem objetos que ele contém, define a ToolStrip.Renderer propriedade para um objeto que herda de ToolStripRenderer. A pintura especificada por o ToolStripRenderer aplica-se ao ToolStrip, bem como aos itens que contém.

Você pode fazer pintura personalizada nos controlos da ToolStrip de várias maneiras. Como acontece com outros controles do Windows Forms, o ToolStrip e o ToolStripItem têm métodos OnPaint substituíveis e eventos Paint. Tal como acontece com a pintura regular, o sistema de coordenadas é relativo à área cliente do controle; ou seja, o canto superior esquerdo do controle é 0, 0. O evento Paint e o método OnPaint para o ToolStripItem comportam-se como outros eventos de pintura de controlo.

A ToolStripRenderer classe tem métodos substituíveis para pintar o fundo, fundo do item, imagem do item, seta do item, texto do item e borda do ToolStrip. Os argumentos de evento para esses métodos expõem várias propriedades, como retângulos, cores e formatos de texto que você pode ajustar conforme desejado.

Para ajustar apenas alguns aspetos de como um item é pintado, normalmente você substitui o ToolStripRenderer.

Se você estiver escrevendo um novo item e quiser controlar todos os aspetos da pintura, substitua o método OnPaint. De dentro OnPaint, você pode usar métodos do ToolStripRenderer.

Por padrão, o ToolStrip é buffer duplo, aproveitando a configuração OptimizedDoubleBuffer.

Construtores

Name Description
ToolStripRenderer()

Inicializa uma nova instância da ToolStripRenderer classe.

Campos

Name Description
Offset2X

Obtém ou define o multiplicador de deslocamento para o dobro do deslocamento ao longo do eixo x.

Offset2Y

Obtém ou define o multiplicador de deslocamento para o dobro do deslocamento ao longo do eixo y.

Métodos

Name Description
CreateDisabledImage(Image)

Cria uma cópia em tons de cinzentos de uma dada imagem.

DrawArrow(ToolStripArrowRenderEventArgs)

Desenha uma seta num ToolStripItem.

DrawButtonBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um ToolStripButton.

DrawDropDownButtonBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um ToolStripDropDownButton.

DrawGrip(ToolStripGripRenderEventArgs)

Desenha uma alça de movimento num ToolStrip.

DrawImageMargin(ToolStripRenderEventArgs)

Desenha o espaço em torno de uma imagem num ToolStrip.

DrawItemBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um ToolStripItem.

DrawItemCheck(ToolStripItemImageRenderEventArgs)

Desenha uma imagem em um ToolStripItem que indica que o item está num estado selecionado.

DrawItemImage(ToolStripItemImageRenderEventArgs)

Desenha uma imagem num ToolStripItem.

DrawItemText(ToolStripItemTextRenderEventArgs)

Desenha texto num ToolStripItem.

DrawLabelBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um ToolStripLabel.

DrawMenuItemBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um ToolStripMenuItem.

DrawOverflowButtonBackground(ToolStripItemRenderEventArgs)

Desenha o fundo para um botão de overflow.

DrawSeparator(ToolStripSeparatorRenderEventArgs)

Tira um ToolStripSeparator.

DrawSplitButton(ToolStripItemRenderEventArgs)

Tira um ToolStripSplitButton.

DrawStatusStripSizingGrip(ToolStripRenderEventArgs)

Tira uma pega de tamanho.

DrawToolStripBackground(ToolStripRenderEventArgs)

Desenha o fundo para um ToolStrip.

DrawToolStripBorder(ToolStripRenderEventArgs)

Desenha a fronteira para um ToolStrip.

DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs)

Desenha o fundo do ToolStripContentPanel.

DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs)

Desenha o fundo do ToolStripPanel.

DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs)

Desenha o fundo do ToolStripStatusLabel.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
Initialize(ToolStrip)

Quando sobrescrito numa classe derivada, permite a inicialização personalizada do dado ToolStrip.

InitializeContentPanel(ToolStripContentPanel)

Inicializa o especificado ToolStripContentPanel.

InitializeItem(ToolStripItem)

Quando sobrescrito numa classe derivada, permite a inicialização personalizada do dado ToolStripItem.

InitializePanel(ToolStripPanel)

Inicializa o especificado ToolStripPanel.

MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
OnRenderArrow(ToolStripArrowRenderEventArgs)

Eleva o RenderArrow evento.

OnRenderButtonBackground(ToolStripItemRenderEventArgs)

Eleva o RenderButtonBackground evento.

OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs)

Eleva o RenderDropDownButtonBackground evento.

OnRenderGrip(ToolStripGripRenderEventArgs)

Eleva o RenderGrip evento.

OnRenderImageMargin(ToolStripRenderEventArgs)

Desenha o fundo do item.

OnRenderItemBackground(ToolStripItemRenderEventArgs)

Eleva o OnRenderItemBackground(ToolStripItemRenderEventArgs) evento.

OnRenderItemCheck(ToolStripItemImageRenderEventArgs)

Eleva o RenderItemCheck evento.

OnRenderItemImage(ToolStripItemImageRenderEventArgs)

Eleva o RenderItemImage evento.

OnRenderItemText(ToolStripItemTextRenderEventArgs)

Eleva o RenderItemText evento.

OnRenderLabelBackground(ToolStripItemRenderEventArgs)

Eleva o RenderLabelBackground evento.

OnRenderMenuItemBackground(ToolStripItemRenderEventArgs)

Eleva o RenderMenuItemBackground evento.

OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs)

Eleva o RenderOverflowButtonBackground evento.

OnRenderSeparator(ToolStripSeparatorRenderEventArgs)

Eleva o RenderSeparator evento.

OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs)

Eleva o OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs) evento.

OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs)

Eleva o RenderStatusStripSizingGrip evento.

OnRenderToolStripBackground(ToolStripRenderEventArgs)

Eleva o RenderToolStripBackground evento.

OnRenderToolStripBorder(ToolStripRenderEventArgs)

Eleva o RenderToolStripBorder evento.

OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs)

Eleva o RenderToolStripContentPanelBackground evento.

OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs)

Eleva o RenderToolStripPanelBackground evento.

OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs)

Eleva o RenderToolStripStatusLabelBackground evento.

ScaleArrowOffsetsIfNeeded()

Aplica os Offset2X valores e Offset2Y para escalar o ícone da seta, se for necessário escalonar com base nas definições de DPI do computador.

ScaleArrowOffsetsIfNeeded(Int32)

Aplica os Offset2X valores e Offset2Y para escalar o ícone da seta com base no valor de DPI especificado.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

evento

Name Description
RenderArrow

Ocorre quando uma seta em um ToolStripItem é renderizada.

RenderButtonBackground

Ocorre quando o fundo de um ToolStripButton é renderizado.

RenderDropDownButtonBackground

Ocorre quando o fundo de um ToolStripDropDownButton é renderizado.

RenderGrip

Ocorre quando a alça de movimento para um ToolStrip é renderizada.

RenderImageMargin

Desenha a margem entre uma imagem e o seu recipiente.

RenderItemBackground

Ocorre quando o fundo de um ToolStripItem é renderizado.

RenderItemCheck

Ocorre quando a imagem de um selecionado ToolStripItem é renderizada.

RenderItemImage

Ocorre quando a imagem de um ToolStripItem é renderizada.

RenderItemText

Ocorre quando o texto para um ToolStripItem é renderizado.

RenderLabelBackground

Ocorre quando o fundo de um ToolStripLabel é renderizado.

RenderMenuItemBackground

Ocorre quando o fundo de um ToolStripMenuItem é renderizado.

RenderOverflowButtonBackground

Ocorre quando o fundo de fundo de um botão de overflow é renderizado.

RenderSeparator

Ocorre quando a ToolStripSeparator é renderizado.

RenderSplitButtonBackground

Ocorre quando o fundo de um ToolStripSplitButton é renderizado.

RenderStatusStripSizingGrip

Ocorre quando o estilo de exibição muda.

RenderToolStripBackground

Ocorre quando o fundo de um ToolStrip é renderizado.

RenderToolStripBorder

Ocorre quando a borda de um ToolStrip é renderizada.

RenderToolStripContentPanelBackground

Desenha o fundo de um ToolStripContentPanel.

RenderToolStripPanelBackground

Desenha o fundo de um ToolStripPanel.

RenderToolStripStatusLabelBackground

Desenha o fundo de um ToolStripStatusLabel.

Aplica-se a

Ver também