不要使用静态变量来保存前一个字符。一般来说,这是不需要的,也是不好的做法。
然后,尽管您的问题有点不清楚,但假设您希望对 的文本进行更改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