修改文本框而不移动光标

时间:2015-10-21 14:56:04

标签: c# winforms

我写过一张支票,限制用户在文本框中输入一个不超过一位小数的权重字段。

private void txtWeight_TextChanged(object sender, EventArgs e)
{
    decimal enteredWeight;
    if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
    {
        decimal roundedWeight = RoundDown(enteredWeight, 1);
        if (enteredWeight != roundedWeight)
        {
            txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
        }
    }
}

RoundDown()的实施无关紧要)

我的问题是,在用户输入小数点后的第二个数字后,它会将其删除很好,但光标会移动到字段的开头。

e.g。

之前:69.2|

然后键入4(例如,不允许69.24

之后:|69.2

我希望文本框中的光标保留在原处......可以这样做吗?

3 个答案:

答案 0 :(得分:4)

您可以保存插入符号的位置,然后在更改文本后重新设置它。

private void txtWeight_TextChanged(object sender, EventArgs e)
{
    decimal enteredWeight;
    if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
    {
        decimal roundedWeight = RoundDown(enteredWeight, 1);
        if (enteredWeight != roundedWeight)
        {
            int caretPos = txtWeight.SelectionStart;
            txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
            txtWeight.SelectionStart = caretPos;
        }
    }
}

答案 1 :(得分:0)

添加:

txtWeight.Select(txtWeight.Text.Length - 1,0)

答案 2 :(得分:-1)

尝试:

txtWeight.CaretIndex = txtBox.Text.Length;

或者:

txtWeight.SelectionStart = txtBox.Text.Length;