我想将输入到文本框中的所有字符都更改为大写。代码将添加字符,但是如何将插入符号向右移动?
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
e.Handled = true;
}
将 的CharacterCasing
属性设置TextBox
为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 更好。
另一种方法是仅更改 KeyChar 本身的值:
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 属性是最简单的解决方案。