温馨提示×

c# textchanged如何实现撤销功能

c#
小樊
84
2024-07-26 17:12:12
栏目: 编程语言

要实现撤销功能,您可以在TextChanged事件处理程序中保存文本框的历史文本,并在需要撤销时将文本框的文本还原为之前保存的历史文本。以下是一个简单的示例代码:

public partial class Form1 : Form
{
    private Stack<string> history = new Stack<string>();
    
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        history.Push(textBox1.Text);
    }

    private void btnUndo_Click(object sender, EventArgs e)
    {
        if (history.Count > 1)
        {
            history.Pop(); // 弹出当前文本
            textBox1.Text = history.Peek(); // 还原为上一次文本
        }
    }
}

在上面的示例中,我们在TextChanged事件处理程序中将文本框的当前文本保存到history栈中。在撤销按钮的Click事件处理程序中,我们检查history栈中是否有保存的历史文本,如果有则弹出当前文本并将文本框的文本设置为上一次保存的文本以实现撤销功能。

0