문제

나는 누군가가 Compact Framework.net 2 SP 2를 사용하여 지금 얻은 문제를 도와 줄 수 있기를 바라고 있습니다.

현재 일련의 텍스트 상자가있는 UI가 있고 각 텍스트 상자에는 데이터베이스 필드의 내용이 표시됩니다. 이것들은 양식의 오른쪽에 스크롤 막대가있는 다른 아래에 표시됩니다. 각 텍스트 박스에는 설정 너비가 있습니다

각 텍스트 상자에 스크롤 막대를 사용하지 않기 위해 보관하고있는 라인 수, 글꼴 크기 및 글꼴에 따라 각 텍스트 상자를 조정하고 싶습니다.

현재 나는 테스트 응용 프로그램에서 이것을 할 수있었습니다.


스크린 샷 :

출력 http://morrislgn.brinkster.net/so/screenshot.jpg의 스크린 샷을 참조하십시오


내 코드 :

'Text used in this example:
'TextBox1qwertyuiop lkjhgfdsazxcvbnm1234567890 TextBo

'x1qwer tyuioplkjhgfdsazxcvb nm1234567890

'qwe
'End of exmaple text.

Me.Textbox2.Text = Me.Textbox1.Text

Dim pobjGraphic As Graphics = Me.Textbox2.Parent.CreateGraphics()
Dim pobjSize As SizeF

'Padding values:
Dim piTop As Int32 = 4 'top of text and top of textbox
Dim piBottom As Int32 = 3 'bottom of text and top of textbox

Dim piLines As Int32 = 0

'Based on the font size chosen by the user, create a font to perform the calculation with.
Dim piFontSize As Single = 10

If Me.CheckBox1.Checked.Equals(True) Then
    piFontSize = 6
ElseIf Me.CheckBox2.Checked.Equals(True) Then
    piFontSize = 8
ElseIf Me.CheckBox3.Checked.Equals(True) Then
    piFontSize = 12
Else
    piFontSize = 10
End If

Dim pobjFont As New Font("Tahoma", piFontSize, FontStyle.Regular)

'Calculate the height of one line.
pobjSize = pobjGraphic.MeasureString("HELLO WORLD", pobjFont)
'Value of pobjSize returned: {Width = 71.0 Height = 13.0}


'Calculate the number of lines          
Dim b As Bitmap
b = New Bitmap(1, 1, Imaging.PixelFormat.Format32bppRgb)

'Calculate the number of lines required to display the text properly based on the lenght of the text the width of the control.
'Length of text to show divide by the width of the textbox
piLines = Graphics.FromImage(b).MeasureString(Me.Textbox2.Text, pobjFont).Width / Me.Textbox2.Width
'Value of piLines returned: 2

If piLines = 0 Then
    piLines = 1
End If

'Calculate the size of the text to be displayed using the margins, height of one line and number of lines.
Me.Textbox2.Height = (pobjSize.Height * piLines) + piTop + piBottom
' value produced: 33 = (13 * 2) + 4 + 3
'set font of text box
Me.Textbox2.Font = pobjFont

마지막으로, P/Invoke를 사용하여 Coredll.dll에 대한 호출을 사용하여이를 달성 할 수 있지만이를 수행하면 응용 프로그램이 충돌합니다.

안녕 여러분,

아래는 요청 된 Pinvoke 코드입니다.

    <Runtime.InteropServices.DllImport("coredll.dll")> _
Private Function SendMessage( _
    ByVal hwnd As IntPtr, ByVal msg As Integer, _
    ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function

<Runtime.InteropServices.DllImport("coredll.dll")> _
Private Function GetCapture() As IntPtr
End Function

<Runtime.InteropServices.DllImport("coredll.dll")> _
Private Function ReleaseCapture() As Boolean
End Function

Public Function GetNumberOfLines(ByVal ptxtCountBox As TextBox) As Integer
    Try
        Dim hnd As IntPtr = New IntPtr

        ptxtCountBox.Capture = True

        ' Capture the textbox handle.
        hnd = GetCapture()
        ptxtCountBox.Capture = False

        ' Get the count of the lines in the box.
        Dim plCount As Integer = SendMessage(ptxtCountBox.Handle, EM_GETLINECOUNT, 0, 0)

        ' Count the number of return lines as we minus this from the total lines to take.
        plCount = plCount - (CharCount(ptxtCountBox.Text, vbCrLf, False))

        plCount += RemoveNonASCIIReturns(ptxtCountBox)

        ReleaseCapture()

        hnd = Nothing

        ' Return the line count.
        Return plCount
    Catch ex As Exception
        GenerateError(msCLASS_NAME, "GetNumberOfLines", ex.Message.ToString)
    End Try
End Function

감사,

모리스

도움이 되었습니까?

해결책

나는 비슷한 질문을하고 주제에 대한 나의 요구를 완전히 충족시키는 답을 얻었습니다! 내 질문에서 STEVO3000의 답변을 확인하십시오..NET Compact 프레임 워크의 레이블 / 텍스트 박스 용 자동 크기

그는이 두 개의 블로그 게시물을 언급했습니다.http://www.mobilepractices.com/2007/12/multi-line-graphicsmeasurestring.html http://www.mobilepractices.com/2008/01/making-multiline-measurestring-work.html

다른 팁

내가 이것의 바닥에 도착했다고 생각합니다.

    Public Function GetNumberOfLines(ByVal pstext As String, ByVal pobjfont As Font, ByVal pobjDimensions As Size) As Decimal
    Dim pslines As String() = Nothing
    'Used to measure the string to be placed into the textbox
    Dim pobjBitMap As Bitmap = Nothing
    Dim pobjSize As SizeF = Nothing

    Try
        Dim psline As String = String.Empty
        Dim pilinecount As Decimal = 0.0
        'Spilt the text based on the number of lines breaks.
        pslines = pstext.Split(vbCrLf)
        For Each psline In pslines
            'Create a graphics image which is used to work out the width of the text.
            pobjBitMap = New Bitmap(1, 1, Imaging.PixelFormat.Format32bppRgb)
            pobjSize = Graphics.FromImage(pobjBitMap).MeasureString(psline, pobjfont)

            'If the width of the text is less than 1.0 then add one to the count. This would incidcate a line break.
            If pobjSize.Width < 1.0 Then
                pilinecount = pilinecount + 1
            Else
                'Based on the dimensions of the text, work out the number of lines. 0.5 is added to round the value to next whole number.
                pilinecount = pilinecount + (Round((pobjSize.Width / pobjDimensions.Width) + 0.5))
            End If
        Next

        'If the line count it less than 1 return one line.
        If pilinecount < 1.0 Then
            Return 1.0
        Else
            Return pilinecount
        End If
    Catch ex As Exception
        Return 1.0
    Finally
        If pslines IsNot Nothing Then
            Array.Clear(pslines, 0, pslines.Length - 1)
            pslines = Nothing
        End If
        If pobjBitMap IsNot Nothing Then
            pobjBitMap.Dispose()
        End If
    End Try
End Function

물론, 그것의 약간의 해킹이지만 지금은 잘 작동하는 것 같습니다! 이를 개선하는 방법에 대한 관찰이나 의견은 환영받는 것 이상입니다.

또한 p/invoke 물건에 대해 문제의 근본 또는 해결책을 발견했습니다. 내 장치의 .NET FX를 업그레이드했으며 문제가 해결 된 것으로 보입니다.

감사

모리스

글쎄, 나는 당신에게 건전하고 똑똑한 솔루션을 제안합니다. 다음은 알고리즘입니다.

  1. 참조를 위해 레이블 컨트롤을 사용하십시오.
  2. 할당 : • 텍스트 상자의 크기는 레이블에 있습니다. • 텍스트 상자의 글꼴을 레이블에 넣습니다. • 라벨의자가 크기 전성기 진실. • TextBox '의 BordersTyle 레이블의 속성. • 텍스트 상자의 원래 크기로 레이블의 최소 크기 속성. • 원래 높이의 크기가 크고 높이가 원래 높이의 크기가 높고 높이의 최대 크기 속성.

  3. 텍스트 상자의 텍스트를 레이블의 텍스트에 할당하십시오.

  4. 지금 : 텍스트 상자의 높이를 prefferdheight-property == true 텍스트 상자의 높이를 높이고 위의 조건이 거짓이 될 때까지 위의 조건을 확인할 때입니다.
  5. 라벨은 이제 폐기 될 수 있습니다.

또한 MSDN 포럼에 비슷한 솔루션을 게시했습니다.http://social.msdn.microsoft.com/forums/en-us/winforms/thread/03fc8e75-fc13-417a-ad8c-d2b26a3a3a4dda]]]]]]

문안 인사. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top