简体   繁体   中英

Vb.Net: Limit the total width of characters entered into a textbox?

Let me be very clear - I am not looking for a static character limit here (Textbox.MaxLength just doesn't cut it.)

I'm making a simple messaging program and I'd like to implement a character limit. The messages are displayed inside a listbox and can't be horizontally scrolled/wrapped. The solution: impose a limit on every message so that users don't accidentally cut off their own messages.

The problem is that 10 small characters are a lot smaller than 10 full width characters. - EG i and W:

  • iiiiiiiiii

  • WWWWWWWWWW

I'd like to find a way to limit the characters entered into the text box by the actual amount of pixels the string is wide. so that:

  • nobody can use all capitals and get cut off, and
  • nobody can type normally and be stopped by the character limit far earlier than neccesary.

For reference, I'm using Verdana 8.25pt for the listbox.

Any suggestions would be appreciated, Thanks.

This should do the trick for you. I've deliberately chosen the keyUp event because the user will see the letter typed and it disappearing.

Private Sub TextBox1_TextChanged(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
    Dim text1 As String = TextBox1.Text
    Dim textboxFont As Font = TextBox1.Font
    Dim textSize As Size = TextRenderer.MeasureText(text1, textboxFont)
    If textSize.Width > TextBox1.ClientRectangle.Width Then
        Dim cursorLocation As Integer = TextBox1.SelectionStart
        TextBox1.Text = TextBox1.Text.Remove(cursorLocation - 1, 1)
        If cursorLocation > TextBox1.Text.Length Then
            TextBox1.SelectionStart = TextBox1.Text.Length
        Else
            TextBox1.SelectionStart = cursorLocation
        End If
    End If
End Sub

Basically what is happening is that the text is rendered (not displayed) using the font of the textbox and measured. If the width of the rendered text is greater than the client area of the textbox, the letter is removed at the point it was typed. This can be anywhere in the text box.

If the cursor is at the end of the text when the letter is removed, .net automatically sets the cursor position to the beginning is a letter is removed. So this sub checks if the initial cursor position was a bigger index than the length of the new textbox contents. If so, the cursor is set to the end again. Otherwise it is moved back 1 because a character was deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM