Alex Alex - 4 months ago 28
Vb.net Question

Issue Using Graphics DrawString On Resize

Goal



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.
MyBase.OnPaint(e)
' Call methods of the System.Drawing.Graphics object.
DrawVerticalString(e)
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)

drawFormat.Dispose()
drawFont.Dispose()
drawBrush.Dispose()
formGraphics.Dispose()
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?

Answer

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
    InitializeComponent()

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

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