如何TextBox
防止在给定位置之前被编辑?
例如,如果 aTextBox
包含字符串:
示例文本:黑猫。
如何防止用户之前编辑任何内容"The"
?
我可以尝试Backspace
使用事件来捕获键KeyPress
,但是如何使用它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
As long as it's a static text item you have pre-defined then I would take this approach:
Have the default value of the texbox as "The black cat " so the user can immediately see it.
Then use the OnGotFocus event of the textbox to remove the first 14 characters (The black cat ) with a space at the end. The user can then freely type what they want (this will preserve anything they have already typed if editing for a second or further time)
TextBox = Right(TextBox, Len(Textbox) - 14)
Then using the OnLostFocus event you can place the 14 characters back at the beginning of the textbox.
TextBox = "The black cat " & TextBox.Value
This method should avoid any complications from the user clicking the mouse anywhere in the field, you also don't need to track the physical data with the Change events.
好的,2路。1)在change事件上,测试“the”是否还在开头,如果不是,添加它。2)将“the”放在文本框之前的标签中。您甚至可以对其进行格式化,使其在用户看来就像是同一个控件。
将您的文本框设置为锁定,然后试试这个。
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
假设:
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
在文本框中编辑预定义字符串 ( )。
您可以使用TextBox_Changed
事件,然后检查其Text
属性。如果它不以“The”开头,则放回“The black cat”。
当您在标记的开始位置之前,以下示例不接受键盘输入,并且当在该位置之前的框内单击时,它会移动到开始位置
这些是针对不需要的操作的 2 个不同答案。您可能希望在 _keypress 和 _click 事件中使用相同的操作
'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