RichTextBox撤消添加空格
我已经为RichTextBox创建了自己的撤消系统,无论何时执行某项操作,都会将撤消操作添加到堆栈中,当您按下撤消操作时,此操作将被撤消。
除了RichTextBoxes之外,这种行为完全适用于我为其实现的所有控件。我已经将系统简化为最简单的元素,无论何时按下删除,它都会将当前选定的文本及其索引添加到堆栈中,当您撤消此操作时,它会将文本放回此索引。
这是删除了最简单元素的代码(就像实际读取文本文件一样):
// 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字符两次。
没有找到相关结果
已邀请:
2 个回复
擅香
冉案