Search code examples
c#winformsundoredo

C#: Unable to undo inserted text


I am programatically adding text in a custom RichTextBox using a KeyPress event:

SelectedText = e.KeyChar.ToString(); 

The problem is that inserting text in such a way doesn't trigger the CanUndo flag.

As such, when I try to Undo / Redo text (by calling the Undo() and Redo() methods of the textbox), nothing happens.

I tried programatically evoking the KeyUp() event from within a TextChanged() event, but that still didn't flag CanUndo to true.

How can I undo text that I insert without having to create lists for Undo and Redo operations ?

Thanks


Solution

  • I finally decided to create my own undo-redo system using stacks.

    Here's a quick overview of how I did it :

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