简体   繁体   中英

textbox multiline, length issues

I have a textbox with multiline set to true. I want to have max characters set to 50 per line with a total of 3 lines . When they reach the 50 characters, I would like it to jump to the second line. I am having some issues and have been struggling with this for a while and wanted to know if anyone can help.

MAX_LINE_COUNT = 3

Private Sub txtMsg_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMsg.KeyDown

    If e.KeyCode = Keys.Enter Then
        e.SuppressKeyPress = (Me.txtMsg.Lines.Length >= MAX_LINE_COUNT)
    End If

End Sub

To effectively handle multiple lines of text with a common max characters per line, then you will need to extend the TextBox class and override several items in the TextBox class. Instead of re-inventing the wheel, I am going to redirect you to the code from an answer to Is there a way to catch maximum length PER LINE and not allow user to input more characters if max length PER LINE has been reached? , since it is not the accepted answer, I will paste the VB.NET translation below:

Public Class MaxPerLineTextBox
  Inherits TextBox
  Public Sub New()
    MyBase.Multiline = True
  End Sub

  Public Overrides Property Multiline() As Boolean
    Get
      Return True
    End Get
    Set
      Throw New InvalidOperationException("Readonly subclass")
    End Set
  End Property

  Public Property MaxPerLine() As System.Nullable(Of Integer)
    Get
      Return m_MaxPerLine
    End Get
    Set
      m_MaxPerLine = Value
    End Set

  End Property

  Private m_MaxPerLine As System.Nullable(Of Integer)

  Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
    If Char.IsControl(e.KeyChar) Then
      MyBase.OnKeyPress(e)
      Return
    End If

    Dim maxPerLine As Integer
    If Me.MaxPerLine.HasValue Then
      maxPerLine = Me.MaxPerLine.Value
    Else
      MyBase.OnKeyPress(e)
      Return
    End If

    Dim activeLine As Integer = Me.GetLineFromCharIndex(Me.SelectionStart)
    Dim lineLength As Integer = Me.SelectionStart - Me.GetFirstCharIndexFromLine(activeLine)

    If lineLength < maxPerLine Then
      MyBase.OnKeyPress(e)
      Return
    End If

    e.Handled = True
  End Sub
End Class

To use the above code you will need to do the following:

  1. Create a new project in your solution to hold the code above.
  2. Paste code above into new project and build it.
  3. Ensure that there are no errors and the project compiles successfully.
  4. The MaxPerLineTextBox control should show up in the toolbox. If it does not, then try restarting Visual Studio.
  5. Drag MaxPerLineTextBox onto your form and set the properties.

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