如何防止给定位置前的TextBox
被编辑?
例如,如果一个TextBox
包含字符串:
Example Text: The black cat.
我如何防止用户编辑"The"
之前的任何内容?
我可以尝试使用KeyPress
事件捕获Backspace
键,但是如何使用MouseClick
防止用户将光标移动到"The"
之前的位置。
RichTextBox
,并像这样保护前缀。Private Sub Form_Load()
Const STR_PREFIX = "Example Text: "
RichTextBox1.Text = STR_PREFIX & "The black cat."
RichTextBox1.SelStart = 0
RichTextBox1.SelLength = Len(STR_PREFIX)
RichTextBox1.SelProtected = True
RichTextBox1.SelLength = 0
End Sub
TextBox = Right(TextBox, Len(Textbox) - 14)
然后使用OnLostFocus事件,您可以将14个字符放回文本框的开头。
TextBox = "The black cat " & TextBox.Value
此方法应避免用户在字段任何位置点击鼠标所产生的任何复杂情况,您也不需要使用Change事件来跟踪物理数据。
Private Sub Text2_KeyDown(KeyCode As Integer, Shift As Integer)
Dim TextMin As Integer
TextMin = 3
If Text2.SelStart > TextMin Then
Text2.Locked = False
ElseIf Text2.SelStart <= TextMin Then
Text2.Locked = True
End If
end sub
'1 form with
' 1 textbox : name=Text1
Option Explicit
Private mintStart As Integer
Private Sub Form_Load()
Text1.Text = "Example text: The black cat"
mintStart = Len("Example text: ")
End Sub
Private Sub Form_Resize()
Text1.Move 0, 0, ScaleWidth, ScaleHeight
End Sub
Private Sub Text1_Click()
With Text1
If .SelStart < mintStart Then
.SelStart = mintStart
End If
End With 'Text1
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If Text1.SelStart < mintStart Then
KeyAscii = 0
End If
End Sub
TextBox_Changed
事件,然后检查它的 Text
属性。如果它不以 "The" 开头,就把 "The black cat" 放回去。好的,有两种方法。1)在更改事件上测试一下,“the”是否仍然在开头,如果不是,则添加它。2)将“the”放在文本框前面的标签中。甚至可以对其进行格式化,使用户看起来像同一控件。
假设:
您想要一个静态的“不可编辑”的字符串在TextBox
控件中
您可以单击此字符串,选择它,它将看起来像文本框中的任何其他文本,唯一的区别是您将无法更改它
TextBox
名称为txt1
Dim str As String Dim oldStr As String Private Sub Form_Load() str = "The" ' static string that you do not want to be edited oldStr = str + " black cat" ' default string to start with in the text box End Sub Private Sub txt1_Change() If UCase(Left(txt1.Text, Len(str))) <> UCase(str) Then ' the static string was edited, so we restore it to previously 'good' value txt1.Text = oldStr Else ' string was changed, but the change is 'good'. Save the new value oldStr = txt1.Text End If End Sub
这段代码将防止预定义的字符串(str
)在文本框中被编辑。
Ctrl+C
复制到剪贴板,这很奇怪。 - wqw