Textbox Line Character Limit






3.38/5 (7 votes)
Oct 31, 2005

73169

552
Limit the number of characters in a multi line textbox.
Introduction
Recently, while I was working on a project, there was a need to limit the amount of text in each line of a multi line textbox to 72 characters. The challenge was to limit the text while the user is typing and to maintain the required formatting. To get this to work, I had to create a class that inherited from TextBox
. In the constructor, I placed a global keyboard trap on the TextBox
. When the text reaches the designated length the program will stop all keyboard characters from displaying on the screen forcing the user to hit the enter key and start a new line.
The code
In the constructor, the program calls the function HookKeyboard
. In this function, the program will trap all keyboard events for the TextBox
:
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Hook all Keyboard Events
HookKeyboard(Me)
End Sub
The function isHooked
in the Keyboard module, where the actual fun begins:
'This function is where you capture the key pressed.
Public Function IsHooked(ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean
Dim zKey As Keys
Dim control As Control
Dim hInstance As Integer
Try
Dim ActiveWin As Integer
'GetActiveWindow determines if the application has focus
ActiveWin = GetActiveWindow
If ActiveWin <> 0 Then
If UBound(frmM.Lines) >= 0 Then
If frmM.Lines(GetTextBoxCurrentLine(frmM) - 1).Length > _
MaxLengthLine Then
'Accept Enter Button
If (Hookstruct.vkCode = zKey.Enter) Then
SendKeys.Send("{Enter}")
Return True
End If
'Accept BackSpace
If (Hookstruct.vkCode = zKey.Back) Then
SendKeys.Send("{BACKSPACE}")
Return True
End If
'Accept Up Arrow
If (Hookstruct.vkCode = zKey.Up) Then
SendKeys.Send("{UP}")
Return True
End If
'Accept Down Arrow
If (Hookstruct.vkCode = zKey.Down) Then
SendKeys.Send("{Down}")
Return True
End If
'Accept Left Arrow
If (Hookstruct.vkCode = zKey.Left) Then
SendKeys.Send("{Left}")
Return True
End If
'Accept Right Arrow
If (Hookstruct.vkCode = zKey.Right) Then
SendKeys.Send("{Right}")
Return True
End If
Return True
End If
End If
End If
Return False
Catch ex As Exception
MsgBox(ex.Message + vbCrLf + ex.StackTrace)
Return False
End Try
End Function