前の文字を保持するために静的変数を使用しないでください。それは必要ではなく、一般的に悪い習慣です。
次に、あなたの質問からは少し不明ですが、 のテキストに変更を加えたいと仮定すると、変更TextBox1
後にテキストを TextBox に戻す必要があるでしょう。
したがって、解決策は次のようになります。
If TextBox1.TextLength > 1 Then
TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1)
ElseIf TextBox1.TextLength = 1 Then
TextBox1.Text = TextBox1.Text.ToUpper()
EndIf
最初の文字を大文字にし、残りを小文字にしたい場合は、上記のコードを次のように変更できます。
If TextBox1.TextLength > 1 Then
TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1).ToLower()
ElseIf TextBox1.TextLength = 1 Then
TextBox1.Text = TextBox1.Text.ToUpper()
EndIf
アップデート
コメントに基づいて、この変更をその場で (つまり、ユーザーが TextBox に入力しているときに) 行う場合は、カーソルも操作する必要があります。基本的に、テキストを変更する前にカーソル位置を保存し、変更後に位置を復元する必要があります。
また、KeyUp
イベントではなくイベントでこれらの変更を実行しKeyPress
ます。これKeyUp
は、キーの押下に応じて TextBox が変更を登録した後に発生します。
Dim startPos as Integer
Dim selectionLength as Integer
' store the cursor position and selection length prior to changing the text
startPos = TextBox1.SelectionStart
selectionLength = TextBox1.SelectionLength
' make the necessary changes
If TextBox1.TextLength > 1 Then
TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1).ToLower()
ElseIf TextBox1.TextLength = 1 Then
TextBox1.Text = TextBox1.Text.ToUpper()
EndIf
' restore the cursor position and text selection
TextBox1.SelectionStart = startPos
TextBox1.SelectionLength = selectionLength