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
仮定:
静的な「編集不可」の文字列を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
) がテキスト ボックスで編集されるのを防ぎます。
テキストボックスをロックに設定してから、これを試してください。
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_Changed
そのText
プロパティを確認できます。「The」で始まらない場合は、「The black cat」を戻します。
わかりました、2way。1) 変更イベントで、「the」がまだ先頭にあるかどうかをテストし、そうでない場合は追加します。2) テキスト ボックスの前のラベルに「the」を入れます。ユーザーに同じコントロールのように見えるようにフォーマットすることもできます。
次の例では、マークされた開始位置の前にいる場合はキーボード入力を受け付けず、その位置の前のボックス内をクリックすると、開始位置に移動します
これらは、不要なアクションに対する 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