logo
vbRad Home
Source Code
Book Reviews
Forum
Links
About Us
Contribute

Compare Databases with SQL Effects Clarity
 
 Prevent Editing of Certain Lines in a TextBox

Posted on
7/13/2001
Author:
Robert Gelb
Email:
Not Shown
Applies To OS:
NT, 9x, 2000
Product:
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
  • 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

Remarks

  • Paste a bunch of text into Text1 and enter what lines are forbidden to edit (separate them by a comma)




Add Your Comment  

Name: Email Address: all fields optional
Notify me via email when someone responds to this message (valid email required).

Enter the word:
 



Comments
#1. By Anonymous. Posted on 7/3/2006 9:04:56 AM
qwerwer
werwer
wer
wer
wer
wer
wer