【问题标题】:Virtual number pad in C#- Is there an elegant way to update Textbox.SelectionStart?C# 中的虚拟数字键盘 - 是否有一种优雅的方式来更新 Textbox.SelectionStart?
【发布时间】:2015-09-01 11:09:49
【问题描述】:

我正在 Windows 窗体中设计一个虚拟数字键盘。请假设我有Del 键来删除textbox 的字符。当我第一次单击textbox 以选择它然后按Del 键时,相对于光标位置正确删除了字符。但更新文本内容后,SelectionStart 属性变为零,我闪烁的光标消失了。我通过在更新textbox 的内容并在最后修改它之前暂时保存它的值来解决这个问题。

tempSelectionStart = enteredTextbox.SelectionStart; //save SelectionStart value temporarily 
enteredTextbox.Text = enteredTextbox.Text.Substring(0, enteredTextbox.SelectionStart - 1)
                    + enteredTextbox.Text.Substring(enteredTextbox.SelectionStart,
                      enteredTextbox.Text.Length - (enteredTextbox.SelectionStart));
enteredTextbox.SelectionStart = tempSelectionStart-1;

我想知道:

  1. 有没有更优雅的方法来解决这个问题?
  2. 第一次按键后如何让光标在文本框中闪烁?

谢谢。

【问题讨论】:

    标签: c# winforms textbox virtual numpad


    【解决方案1】:

    改用 SelectedText 属性:

    private void DeleteButton_Click(object sender, EventArgs e) {
        if (textBox1.SelectionLength == 0) textBox1.SelectionLength = 1;
        textBox1.SelectedText = "";
        textBox1.Focus();
    }
    
    private void BackspaceButton_Click(object sender, EventArgs e) {
        if (textBox1.SelectionLength == 0) {
            if (textBox1.SelectionStart > 0) {
                textBox1.SelectionStart--;
                textBox1.SelectionLength = 1;
            }
        }
        textBox1.SelectedText = "";
        textBox1.Focus();
    }
    

    【讨论】:

    • 如果你想让 Del 键作为 Backspace 并删除光标左侧的字符,只需从 SelectionStart 中减去一个。还有其他方法吗?
    • 叹息。您仍然使用 SelectionText 属性。
    • 亲爱的Passant,你能指导我通过SelectedText属性来做吗?
    • 我发布了代码,不知道你还想要什么。
    • 亲爱的帕桑特,我很感激你。
    猜你喜欢
    • 2022-06-11
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多