VB - Limit TextBox Line Length
Someone asked once if it would be possible to limit the length of each line in a text box to 10 characters. This is the code I came up with:
VB Code:
Option Explicit
'API Declarations:
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long
'Constant Delcarations
Private Const EM_LINEINDEX = &HBB
Private Const EM_LINELENGTH = &HC1
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim lLen As Long
'Get the length of the current line:
lLen = SendMessage(Text1.hwnd, EM_LINELENGTH, EM_LINEINDEX, 0&)
'If length is 10, don't allow more characters:
If lLen = 10 And KeyAscii <> vbKeyReturn And KeyAscii <> vbKeyBack Then
KeyAscii = 0
End If
End Sub
Re: VB - Limit TextBox Line Length
Great Code!
One issue:
I modified the code so that when the line reaches a certain length (10 for this example), text1.text = text1.text & VBCRLF so that the new text starts on the next line. If i then go back up to the previous line, I can type the 11th character and keep typing past the original 10 characters. Is there any way to prevent this?
Quote:
Originally posted by The Hobo
Someone asked once if it would be possible to limit the length of each line in a text box to 10 characters. This is the code I came up with:
VB Code:
Option Explicit
'API Declarations:
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long
'Constant Delcarations
Private Const EM_LINEINDEX = &HBB
Private Const EM_LINELENGTH = &HC1
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim lLen As Long
'Get the length of the current line:
lLen = SendMessage(Text1.hwnd, EM_LINELENGTH, EM_LINEINDEX, 0&)
'If length is 10, don't allow more characters:
If lLen = 10 And KeyAscii <> vbKeyReturn And KeyAscii <> vbKeyBack Then
KeyAscii = 0
End If
End Sub
:) :eek: