C#中的虚拟数字键盘 - 是否有一种优雅的方式来更新Textbox.SelectionStart?

时间:2015-09-01 11:09:49

标签: c# winforms textbox virtual numpad

我正在设计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. 首次按下键后,如何在文本框中按住光标?
  3. 感谢。

1 个答案:

答案 0 :(得分:2)

改为使用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();
}