C#:无法撤消插入的文本

Hus*_*lil 6 c# undo redo winforms

我使用KeyPress事件以编程方式在自定义RichTextBox中添加文本:

SelectedText = e.KeyChar.ToString(); 
Run Code Online (Sandbox Code Playgroud)

问题是以这种方式插入文本不会触发CanUndo标志.

因此,当我尝试撤消/重做文本时(通过调用文本框的Undo()和Redo()方法),没有任何反应.

我尝试以编程方式从TextChanged()事件中唤起KeyUp()事件,但仍未将CanUndo标记为true.

如何撤消插入的文本而不必为撤消和重做操作创建列表?

谢谢

Hus*_*lil 3

我最终决定使用堆栈创建自己的撤消重做系统。

以下是我的做法的快速概述:

private const int InitialStackSize = 500;    
private Stack<String> undoStack = new Stack<String>(InitialStackSize);
private Stack<String> redoStack = new Stack<String>(InitialStackSize); 

private void YourKeyPressEventHandler(...)
{
        // The user pressed on CTRL - Z, execute an "Undo"
        if (e.KeyChar == 26)
        {
            // Save the cursor's position
            int selectionStartBackup = SelectionStart;

            redoStack.Push(Text);
            Text = undoStack.Pop();

            // Restore the cursor's position
            SelectionStart = selectionStartBackup;
        }
        // The user pressed on CTRL - Y, execute a "Redo"
        if (e.KeyChar == 25)
        {
            if (redoStack.Count <= 0)
                return;

            // Save the cursor's position
            int selectionStartBackup = SelectionStart + redoStack.ElementAt(redoStack.Count - 1).Length;

            undoStack.Push(Text);
            Text = redoStack.Pop();

            // Restore the cursor's position
            SelectionStart = selectionStartBackup;

            return;
        }    

        undoStack.Push(Text);
        SelectedText = e.KeyChar.ToString();  
}
Run Code Online (Sandbox Code Playgroud)