Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRestrict a TextBox to at most four lines using the KeyPress event
KeywordsTextBox, restrict, lines, carriage return
CategoriesControls
 
In the KeyPress event handler, see what the user is typing. If it is a carriage return, see how many lines the new value would have. If it would have more than four lines, set KeyAscii = 0 to disallow the new character.

If the user types Control-V, see what the new value would be after pasting the clipboard's contents. If the new value has more than four lines, set KeyAscii = 0 to disallow the new character.

 
Private Sub txtFourLines_KeyPress(KeyAscii As Integer)
Const ASC_CR = 13   ' ASCII value of vbCr.
Const CTL_V = 22    ' ASCII value of Control-V.
Dim new_value As String

    ' See what the user is typing.
    If KeyAscii = ASC_CR Then
        ' Carriage return.
        ' See if the text already contains
        ' more than 3 lines. Remember Split
        ' returns a zero-based array so UBound
        ' returns 1 less than the count.
        If UBound(Split(txtFourLines.Text, vbCr)) > 2 Then
            ' Disallow this character.
            KeyAscii = 0
        End If
    ElseIf KeyAscii = CTL_V Then
        ' Control-V.
        ' See what the new value will be.
        new_value = _
            Left$(txtFourLines.Text, txtFourLines.SelStart) _
                & _
            Clipboard.GetText & _
            Mid$(txtFourLines.Text, txtFourLines.SelStart + _
                txtFourLines.SelLength + 1)

        ' See how many lines this would be.
        If UBound(Split(new_value, vbCr)) > 3 Then
            ' Disallow this character.
            KeyAscii = 0
        End If
    End If
End Sub
 
Note that the user could still use the TextBox's popup menu to paste text. To prevent that, subclass the TextBox and intercept the WM_CONTEXTMENU message.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated