I've created my own undo system for the RichTextBox whereby whenever you do something an undo action is added to a stack, and when you press undo, this action is undone.
This behavior works perfectly with all controls I've implemented it for, except for RichTextBoxes. I have reduced the system down to its simplest elements, where whenever you press delete, it adds the current selected text and its index to a stack, and when you undo this, it puts the text back at this index.
Here is the code with the simplest elements stripped out (like the actual reading of the text file):
// Struct I use to store undo data
public struct UndoSection
{
public string Undo;
public int Index;
public UndoSection(int index, string undo)
{
Index = index;
Undo = undo;
}
}
public partial class Form1 : Form
{
// Stack for holding Undo Data
Stack<UndoSection> UndoStack = new Stack<UndoSection>();
// If delete is pressed, add a new UndoSection, if ctrl+z is pressed, peform undo.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
UndoStack.Push(new UndoSection(textBox1.SelectionStart, textBox1.SelectedText));
else if (e.Control && e.KeyCode == Keys.Z)
{
e.Handled = true;
UndoMenuItem_Click(textBox1, new EventArgs());
}
}
// Perform undo by setting selected text at stored index.
private void UndoMenuItem_Click(object sender, EventArgs e)
{
if (UndoStack.Count > 0)
{
// Save last selection for user
int LastStart = textBox1.SelectionStart;
int LastLength = textBox1.SelectionLength;
UndoSection Undo = UndoStack.Pop();
textBox1.Select(Undo.Index, 0);
textBox1.SelectedText = Undo.Undo;
textBox1.Select(LastStart, LastLength);
}
}
}
However if you select just the
from one line, and more text below like this: , then press delete, and then undo, it seems to undo this
character twice.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…