view raw
Alex Alex - 10 months ago 77 Question

Issue Using Graphics DrawString On Resize


I want to display a vertical text on the left of a user control to let a user know which product they are creating/editting. Like so:

enter image description here

How am I building it?

This user control is made up of three controls.

  1. Label with text "Product Information". Dock=Top

  2. User Control with a vertical draw string text of "Product #1". Dock=Left

  3. Table Layout panel which contains X amount of user controls inside it. Dock=Fill

Here's the design view:

enter image description here

Here is the code for my product name user control that draws "Product #1"

Public Class uProductName
Public drawString As String = "Product #1"

Protected Overrides Sub OnPaint(e As PaintEventArgs)
' Call the OnPaint method of the base class.
' Call methods of the System.Drawing.Graphics object.
End Sub

Public Sub DrawVerticalString(ByVal e As PaintEventArgs)
Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
Dim drawFont As New System.Drawing.Font("Arial", 20)
Dim drawBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Black)
Dim stringSize As New SizeF
stringSize = e.Graphics.MeasureString(drawString, drawFont)
Dim x As Single = (Me.Width / 2) - (stringSize.Height / 2)
Dim y As Single = (Me.Height / 2) - (stringSize.Width / 2)
Dim drawFormat As New System.Drawing.StringFormat
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical
formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat)

End Sub
End Class

Current Problem

When I start selecting buttons, the table layout panel expands to display more selections and the "Product #1" text starts to glitch. See below:

enter image description here

I tried to set the "Double Buffer" property to true and didn't the result. Any advice?


You need to set ControlStyles.ResizeRedraw style for your control to indicate whether the control redraws itself when resized.

Also Instead of using CreateGraphics(), use the graphics object of OnPaint method and never dispose it, because it doesn't belong to you.

Public Sub New()
    ' If the base class is Control, comment the next line

    Me.SetStyle(ControlStyles.ResizeRedraw, True)
End Sub

Public Sub DrawVerticalString(ByVal e As PaintEventArgs)
    Dim formGraphics As System.Drawing.Graphics = e.Graphics
End Sub