Search code examples
vb.netwinformsgraphicsword-wraptextrenderer

How to wrap long word with TextRenderer DrawText in vb.net


How can I draw a long word on a form with word breaking using TextRenderer DrawText() in vb.net? I thought it's a simple question and I tried all TextFormatFlags combinations but I can't find nothing solution. Can anyone help? Here is a sample:

sText = "C:\Users\abiga\OneDrive\Works\AdreNDSzinkron\bin\Debug\AdreService.exe"
TextRenderer.DrawText(e.Graphics, sText, Font, New Rectangle(0, 0, Me.Width, Me.Height),
                      Me.Color,TextFormatFlags.<what is the correct flag?>) 

I need this (nothing clipped):

C:\Users\abiga\OneDrive\Works\Adr
eNDSzinkron\bin\Debug\AdreService
.exe

Wrong solutions:

C:\Users\abiga\OneDrive\Works\Adr
C:\Users\abiga\OneDrive\Works\...
C:\Users\ab...bug\AdreService.exe

Thank you for your help!


Solution

  • First try TextFormatFlags.WordBreak or TextFormatFlags.TextBoxControl as your flags.

    The docs say:

    WordBreak: Breaks the text at the end of a word

    TextBoxControl: Specifies the text should be formatted for display on a TextBox control

    Combining these flags should give the expected result.

    If that doesnt work then try using Graphics.DrawString instead:

    e.Graphics.DrawString(sText, Font, Me.Color, New RectangleF(0, 0, Me.Width, Me.Height))