8

我想将输入到文本框中的所有字符都更改为大写。代码将添加字符,但是如何将插入符号向右移动?

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
    textBox3.Text += e.KeyChar.ToString().ToUpper();
    e.Handled = true;
}
4

6 回答 6

18

将 的CharacterCasing属性设置TextBoxUpper; 那么您不需要手动处理它。

请注意,即使输入插入符号位于字符串的中间(大多数用户会觉得非常混乱) ,它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;
于 2009-07-24T14:19:01.250 回答
13
            tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
            tbNumber.SelectionLength = 0;
于 2010-03-22T19:06:27.110 回答
2
private void txtID_TextChanged(object sender, EventArgs e)
{
    txtID.Text = txtID.Text.ToUpper();
    txtID.SelectionStart = txtID.Text.Length;
}
于 2012-08-13T07:01:26.410 回答
1

这将保留插入点的位置(但我个人会选择 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,我目前手头没有编译器。

于 2009-07-24T14:23:15.520 回答
1

如果您必须手动执行此操作,您可以使用

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 更好。

于 2009-07-24T14:24:39.650 回答
0

另一种方法是仅更改 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 属性是最简单的解决方案。

于 2009-07-24T15:56:11.763 回答