开发者

Display Fixed Width Text in Winforms using VB.NET

I need to write some fixed-width font (i.e Courier New or Consolas) text to a .net Winforms window in the Paint event - not using a label or any other winforms control - rather using a graphics object method to render the text onto the form's client area.

I am having difficulty aligning text on different lines under headings even though it is fixed width font. How can I get a precise measurement of the width of a single character in the fixed-width font? How can I get 2 lines to print out aligned horizontally in successive text out calls?

For example:

Heading 1          Heading 2

Short              Other text A bit longer       Still aligned?

I need a separate call to render each cell of text under Heading 2. For argument's sake - let's say column 1 items are printed in black and column 2 are printed in blue - we can't use the same text out call for t开发者_如何学Gohe entire line.


Graphics.MeasureString may be what you are looking for.


Ok so here is the code that works the way I want using MeasureString. A string is printed twice. One time using a single call to DrawString. The second time, character by character in a loop. What I needed was that the 2 strings should appear identical but I was having trouble getting the correct horizontal position of each char when drawing the second string. You can put this code into the Paint event of a form to try it out (set the form font to Consolas or other fixed width font):

Dim i As Single
Dim sf As StringFormat
Dim String1 As String = "Here is out test string"
Dim CharSizeF As SizeF

sf = StringFormat.GenericTypographic

CharSizeF = e.Graphics.MeasureString(String1, Me.Font, 10000, sf)
CharSizeF.Width /= String1.Length

e.Graphics.DrawString(String1, Me.Font, Brushes.Black, 0, 0, sf)

For Each c As Char In String1
    e.Graphics.DrawString(c.ToString, Me.Font, Brushes.Black, i * CharSizeF.Width, CharSizeF.Height, sf)
    i += 1
Next

Display Fixed Width Text in Winforms using VB.NET

Microsoft also helped with:

http://msdn.microsoft.com/en-us/library/957webty.aspx To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat and pass GenericTypographic. Also ensure the TextRenderingHint for the Graphics is AntiAlias.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜