我已经为RichTextBox创建了我自己的撤消系统,因此无论何时您执行某项操作时撤消操作都会添加到堆栈中,并且当您按下撤消操作时,此操作将被撤消。RichTextBox撤消添加空格
此行为完全适用于我为其实施的所有控件,RichTextBoxes除外。我已经将系统简化为最简单的元素,无论何时按下delete,它都会将当前选定的文本及其索引添加到堆栈中,并且在撤消此操作时,会将文本放回到此索引处。
这里是剥离出来的简单元素的代码(如文本文件的实际读取):
// 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);
}
}
}
不过,如果你只选择从一条线的\ n和下面更多的文字是这样:,然后按删除,然后撤消,它似乎撤消这个\ n字符两次。
你有通过代码?可能的话,输出堆栈上的所有东西,然后重新堆叠堆栈? – MunkiPhD 2010-11-22 01:55:39