c# - 不移动光标修改文本框

标签 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() 的实现无关紧要)

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

例如

之前:69.2|

然后输入 4(例如 69.24,这是不允许的)

之后:|69.2

我希望文本框中的光标保持在原来的位置...这可以做到吗?

最佳答案

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

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;
        }
    }
}

关于c# - 不移动光标修改文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33262657/

相关文章:

c# - 我可以像在 C# 中那样在 Java 中创建扩展吗?

C# 集合类 - 是或否

c# - 链接按钮控件使用asp.net

c# - 如何阻止我的 UI 卡住?

c# - 如何在 C# 中实现分段文本框,强制用户以特定格式输入值?

c# - 使用 MediaPlayer 控件自动播放下一个文件(AxWindowsMediaPlayer)

c# - C# 中具有具体 setter 的抽象 getter

c# - 无法将字符串隐式转换为 bool 值

c# - 如何从数据集中设置 DataGridViewComboBoxColumn 值

c# - 与 C#/WinForms 中经过深度优化的 GDI 代码相比,SharpDX 可以带来多少改进?