Download
the source code for this article (2 kb)
One of the question asked often in the newsgroups is how to prevent the
user from editing certain lines in a textbox. We've seen ridiculous solutions, like
counting vbCrLf in the textbox, etc...
The right way to do it is to call a Windows API function to find out what
line the cursor is located, then apply editing rules. Check out the example below.
- Start New Project (Standard EXE)
- Add 2 textboxes to the form
- Leave the name of the first textbox that will contain the text as is, but set the
Multiline property to True and resize it to the height of the form
- Call the second textbox txtPrevent
| Add the following code to the Form |
'declarations
Private Const EM_LINEFROMCHAR = &HC9
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
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim iCurrentLineNumber As Long
Dim sForbiddenLines() As String
Dim x As Long
'function call
iCurrentLineNumber = SendMessage(Text1.hwnd, EM_LINEFROMCHAR, Text1.SelStart, 0&)
'increment, because the API counts lines starting from zero
iCurrentLineNumber = iCurrentLineNumber + 1
'split the forbidden string into an array
sForbiddenLines = Split(txtPrevent.Text, ",")
'loop through the forbidden lines and check what lines are verbotten
For x = 0 To UBound(sForbiddenLines)
If iCurrentLineNumber = Val(sForbiddenLines(x)) Then
'This line is forbidden to edit, cancel the entry
KeyAscii = 0
Exit For
End If
Next
End Sub
- Paste a bunch of text into Text1 and enter what lines are forbidden to edit (separate them by a comma)