Winform Richtextbox控件本身并不直接支持撤銷和重做功能,但可以通過添加自定義的撤銷和重做功能來實現該功能。以下是一種實現方式:
public class UndoRedoStack
{
private Stack<string> undoStack = new Stack<string>();
private Stack<string> redoStack = new Stack<string>();
public void AddOperation(string operation)
{
undoStack.Push(operation);
redoStack.Clear();
}
public string Undo()
{
if (undoStack.Count == 0)
return null;
string operation = undoStack.Pop();
redoStack.Push(operation);
return operation;
}
public string Redo()
{
if (redoStack.Count == 0)
return null;
string operation = redoStack.Pop();
undoStack.Push(operation);
return operation;
}
}
UndoRedoStack undoRedoStack = new UndoRedoStack();
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
undoRedoStack.AddOperation(richTextBox1.Text);
}
private void undoButton_Click(object sender, EventArgs e)
{
string operation = undoRedoStack.Undo();
if (operation != null)
{
richTextBox1.Text = operation;
}
}
private void redoButton_Click(object sender, EventArgs e)
{
string operation = undoRedoStack.Redo();
if (operation != null)
{
richTextBox1.Text = operation;
}
}
通過以上步驟,就可以在Winform Richtextbox控件中實現撤銷和重做功能。當用戶進行文本編輯操作時,可以通過點擊撤銷按鈕來撤銷上一步操作,通過點擊重做按鈕來重做上一步撤銷的操作。