不要使用静态变量来保存前一个字符。一般来说,这是不需要的,也是不好的做法。
然后,虽然您的问题有点不清楚,但假设您希望对 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
更新
基于 cmets,如果您想即时进行此更改(即当用户在 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