Prevent Editing of Certain Lines in a TextBox

Applies To

OS:
VB:
NT, 9x, 2000
5, 6

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.



Directions
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

Remarks