如何将文本框插入符移动到右侧

8

我想把文本框中输入的所有字符都转换成大写字母。代码可以添加字符,但如何将插入符号移到右边?

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

你正在使用哪个GUI框架?这是Win Forms吗?WPF?Silverlight? - Muad'Dib
@monkey_boys-我希望我的更改没有改变你的意思。 - John MacIntyre
请注意,textBox3.Text += e.KeyChar.ToString().ToUpper() 将始终将新字符添加到文本框的末尾,即使插入符号在文本中间也是如此。 - Fredrik Mörk
@John MacIntyre- 我认为他的意思是希望光标位于新插入字符的右侧。 - erelender
6个回答

18

TextBoxCharacterCasing 属性设置为 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;

+1:我提供了另一种答案,因为它在其他情况下可能会有用。 - Binary Worrier

13
            tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
            tbNumber.SelectionLength = 0;

这是在用户输入文本之前添加文本的绝佳方式。 - Todd Moses

2
private void txtID_TextChanged(object sender, EventArgs e)
{
    txtID.Text = txtID.Text.ToUpper();
    txtID.SelectionStart = txtID.Text.Length;
}

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,我目前手头没有编译器。


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


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属性是最简单的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接