繁体   English   中英

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

[英]Virtual number pad in C#- Is there an elegant way to update Textbox.SelectionStart?

我正在设计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. 第一次按下键后,如何在文本框中保持光标闪烁?

谢谢。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM