简体   繁体   English

c# 中的鼠标可点击退格按钮

[英]mouse clickable backspace button in c#

I wanted to make a backspace button for my calculator app in windows form the problem is it deletes the character to the right of the cursor, not the left what can I do?我想在 windows 中为我的计算器应用程序制作一个退格按钮,问题是它删除了 cursor 右侧的字符,而不是左侧我该怎么办?

 private void DeleteTextValue()
    {
        //if we don't have any value to delete, return 
        if (this.UserInput.Text.Length < this.UserInput.SelectionStart + 1)
            return;

        //remember cursor location
        var selectionStart = this.UserInput.SelectionStart;

        //delete the char to the right of the cursor
        this.UserInput.Text = this.UserInput.Text.Remove(this.UserInput.Text.Length-1, 1);

        //restore the cursor location
        this.UserInput.SelectionStart = selectionStart;

        //unhighlight the text
        this.UserInput.SelectionStart = 0 ;
    }

Try this, I used substring instead of remove.试试这个,我使用 substring 而不是删除。

private void DeleteTextValue()
    {
        //if we don't have any value to delete, return 
        if (this.UserInput.Text.Length < this.UserInput.SelectionStart + 1)
            return;

        //remember cursor location
        var selectionStart = this.UserInput.SelectionStart;

        //delete the char to the right of the cursor
        //this.UserInput.Text = this.UserInput.Text.Remove(this.UserInput.Text.Length - 1, 1);
                    
        if (UserInput.SelectedText.Length > 0)
        {
            UserInput.Text = this.UserInput.Text.Substring(0, this.UserInput.SelectionStart) + "" + this.UserInput.Text.Substring(this.UserInput.SelectionStart + this.UserInput.SelectionLength);
            selectionStart = selectionStart - this.UserInput.SelectionLength; 
        }
        else
        {
            UserInput.Text = this.UserInput.Text.Substring(0, this.UserInput.SelectionStart - 1) + "" + this.UserInput.Text.Substring(this.UserInput.SelectionStart);
            selectionStart = selectionStart - 1;
        }
        UserInput.Focus();
        //restore the cursor location
        this.UserInput.SelectionStart = selectionStart;

        //unhighlight the text
         this.UserInput.SelectionLength= 0;
    }

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

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