Calculate the height of a Label control given a fixed width

G

Gary

Hi,

I would like to autosize a Label's height based on a fixed width. It seems
that .NETCF has dropped support for this overload.. but anyway that
would probably not be correct for the 'system' label using system text
rendering.

PS: I am using .NET CF2, so if there is another way that I have missed
please let me know.

So I am trying to PInvoke the calculation but not having any luck..

When I call this on the device I get a NotSupportedException thrown.

(I have also tried declaring GetTextExtentExPointW)

<System.Runtime.InteropServices.DllImport("coredll.dll",
SetLastError:=True)> _
Private Shared Function GetTextExtentExPoint( _
ByVal hdc As IntPtr, _
ByVal lpszStr As String, _
ByVal cchString As Integer, _
ByVal nMaxExtent As Integer, _
ByRef lpnFit As Integer, _
ByVal alpDx As Integer, _
ByRef lpSize As Size) As Long
End Function



When I call this in the designer, I get a valid result but it is not taking
into
consideration any wrapping. So the width returned is greater than nMaxExtent
and the hight is only a single line.

<System.Runtime.InteropServices.DllImport("gdi32.dll",
EntryPoint:="GetTextExtentExPointW", SetLastError:=True)> _
Private Shared Function gdi32_GetTextExtentExPoint( _
ByVal hdc As IntPtr, _
ByVal lpszStr As String, _
ByVal cchString As Integer, _
ByVal nMaxExtent As Integer, _
ByRef lpnFit As Integer, _
ByVal alpDx As Integer, _
ByRef lpSize As Size) As Long
End Function

Dim thetext As String = "This is a really long line of text that should wrap
onto a second line."
Dim lpnFit As Integer
Dim sz As Size
dim nMaxExtent As Integer = 160

' I have a valid hdc and have SelectObject()'d the font before I call this
gdi32_GetTextExtentExPoint (hdc, thetext, thetext.Length, nMaxExtent,
lpnFit, 0, sz)


So any help using GetTextExtentExPoint() even on desktop windows would be
really helpful too.

Thanks,

Gary
 
G

Gary

Thanks Alex, I had actually tried an older version from your blog that
wasn't as accurate,
but this one seems to be better so far.

Still I don't think that this approach will ever be 100% accurate as you are
comparing
GDI+ measurements with GDI rendering.. at least on the desktop that would be
a correct
statement, can only assume on mobile it is the same. I will probably go so
far as to write
a fully managed label class with autosize built in.. but in the end it will
require PInvoke for
everything anyway, as even with CF2 I cannot get anti-aliased or cleartype
quality text out
of Graphics.DrawString(). :-(

Cheers,

Gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top