Visual Basic Programming Code Examples
Visual Basic > Forms Code Examples
Preventing specific lines in a textbox from being edited
Preventing specific lines in a textbox from being edited
The following code shows you how to prevent specific lines in a textbox from being edited by the user.
Option Explicit
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
'Purpose : Prevents users from editing specific lines in a MultiLine textbox
'Inputs : txtProtect The textbox being edited
' KeyAscii The Ascii value of the KeyPressed (from the KeyPress event of the textbox)
' avLinesToProtect The list of lines to protect
'Outputs : Returns the icon
'Example : Below is an example of how to use this function (place in form containing a multiline textbox):
'Private Sub Form_Load()
' Text1.Text = "This Line is PROTECTED!!!" & vbNewLine & "This Line is PROTECTED!!!" & vbNewLine & "This Line is PROTECTED!!!" & vbNewLine & "This Line in NOT PROTECTED"
'End Sub
'Private Sub Text1_KeyPress(KeyAscii As Integer)
' KeyAscii = TextBoxProtectLines(Text1, KeyAscii, 1, 2, 3) 'Protect first three lines
'End Sub
'Revisions :
Function TextBoxProtectLines(txtProtect As TextBox, KeyAscii As Integer, ParamArray avLinesToProtect()) As Integer
Dim lStartLine As Long, lEndLine As Long
Dim sLinesToProtect As String
Const EM_LINEFROMCHAR = &HC9
On Error GoTo ErrFailed
'Return the KeyAscii value
TextBoxProtectLines = KeyAscii
'Determine the current line/s the user is editing
lStartLine = SendMessage(txtProtect.hwnd, EM_LINEFROMCHAR, txtProtect.SelStart, 0&) + 1
lEndLine = SendMessage(txtProtect.hwnd, EM_LINEFROMCHAR, txtProtect.SelStart + txtProtect.SelLength, 0&) + 1
sLinesToProtect = Join(avLinesToProtect, "|")
'split the forbidden string into an array
If Len(sLinesToProtect) Then
sLinesToProtect = "|" & sLinesToProtect
If InStr(1, sLinesToProtect, "|" & lStartLine) > 0 Or InStr(1, sLinesToProtect, "|" & lEndLine) > 0 Then
'User is trying to edit a protected line, return an empty ascii value
TextBoxProtectLines = 0
End If
End If
Exit Function
ErrFailed:
Debug.Print "Error in TextBoxProtectLines: " & Err.Description
On Error GoTo 0
End Function