我想把文本框中输入的所有字符都转换成大写字母。代码可以添加字符,但如何将插入符号移到右边?
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
e.Handled = true;
}
将 TextBox
的 CharacterCasing
属性设置为 Upper
,这样你就不需要手动处理了。
请注意,textBox3.Text += e.KeyChar.ToString().ToUpper();
将把新字符追加到字符串末尾,即使输入光标在字符串中间(大多数用户会觉得非常困惑)。因此,我们也不能假定输入光标应该在输入字符后出现在字符串末尾。
如果您确实希望在代码中完成此操作,可以使用以下代码:
// needed for backspace and such to work
if (char.IsControl(e.KeyChar))
{
return;
}
int selStart = textBox3.SelectionStart;
string before = textBox3.Text.Substring(0, selStart);
string after = textBox3.Text.Substring(before.Length);
textBox3.Text = string.Concat(before, e.KeyChar.ToString().ToUpper(), after);
textBox3.SelectionStart = before.Length + 1;
e.Handled = true;
tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
tbNumber.SelectionLength = 0;
private void txtID_TextChanged(object sender, EventArgs e)
{
txtID.Text = txtID.Text.ToUpper();
txtID.SelectionStart = txtID.Text.Length;
}
这将保留插入点的位置(但个人建议采用Fredrik Mörk提供的答案)
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
int selStart = textBox3.SelectionStart;
textBox3.Text += e.KeyChar.ToString().ToUpper();
textBox3.SelectionStart = selStart;
e.Handled = true;
}
SelectionStart 可能实际上被称为 SelStart,我目前手头没有编译器。
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
textBox3.SelectionStart = textBox3.Text.Length;
e.Handled = true;
}
但是前面的代码将新字符插入到文本末尾。如果您想在光标所在位置插入它:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
int selStart = textBox3.SelectionStart;
textBox3.Text = textBox3.Text.Insert(selStart,e.KeyChar.ToString().ToUpper());
textBox3.SelectionStart = selStart + 1;
e.Handled = true;
}
这段代码将新字符插入到光标位置,并将光标移动到新插入字符的左侧。
但我仍然认为设置CharacterCasing更好。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
if ((int)e.KeyChar >= 97 && (int)e.KeyChar <= 122) {
e.KeyChar = (char)((int)e.KeyChar & 0xDF);
}
}
虽然使用CharacterCasing属性是最简单的解决方案。
textBox3.Text += e.KeyChar.ToString().ToUpper()
将始终将新字符添加到文本框的末尾,即使插入符号在文本中间也是如此。 - Fredrik Mörk