我的textbox
multiline
设置为true。我希望max characters
设置为每行50 ,总共3行。当它们达到50个字符时,我希望它跳到第二行。
我有一些问题,一直在努力解决这个问题,想知道是否有人可以提供帮助。
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
答案 0 :(得分:2)
要有效处理每行常用最大字符数的多行文本,您需要扩展TextBox
类并覆盖TextBox
类中的多个项目。我不打算重新发明轮子,而是将你重定向到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?答案的代码,因为它不是公认的答案,我将在下面粘贴VB.NET翻译:
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
要使用上述代码,您需要执行以下操作: