Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 912
Hussein Khalil Avatar asked Mar 24 '11 15:03

Hussein Khalil


2 Answers

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();  
}
like image 170
Hussein Khalil Avatar answered Sep 21 '22 06:09

Hussein Khalil


It's just an idea but what if you set the caret position to where you would insert your text and instead of modifying the Text property, just send the keys?

SendKeys.Send("The keys I want to send");

There are bound to be quirks but as I said, it's just an idea.

like image 23
Peter Avatar answered Sep 21 '22 06:09

Peter