WinForm之Command
时间: 2024-01-10 14:02:32 浏览: 122
WinForm.Command.pdf of C1 studio
好的,下面是一个简单的C# WinForm文本编辑器中实现撤销和重做操作的代码:
```csharp
// 定义命令接口
public interface ICommand
{
void Execute();
}
// 定义撤销命令
public class UndoCommand : ICommand
{
private readonly TextBox _textBox;
public UndoCommand(TextBox textBox)
{
_textBox = textBox;
}
public void Execute()
{
_textBox.Undo();
}
}
// 定义重做命令
public class RedoCommand : ICommand
{
private readonly TextBox _textBox;
public RedoCommand(TextBox textBox)
{
_textBox = textBox;
}
public void Execute()
{
_textBox.Redo();
}
}
// 在窗体中关联命令和控件事件
public partial class Form1 : Form
{
private readonly Stack<ICommand> _undoStack = new Stack<ICommand>();
private readonly Stack<ICommand> _redoStack = new Stack<ICommand>();
public Form1()
{
InitializeComponent();
// 关联撤销命令和Ctrl+Z快捷键
var undoCommand = new UndoCommand(textBox1);
var undoKey = new KeyEventArgs(Keys.Z | Keys.Control);
textBox1.KeyDown += (sender, e) =>
{
if (e.KeyCode == undoKey.KeyCode && e.Modifiers == undoKey.Modifiers)
{
if (_undoStack.Count > 0)
{
var command = _undoStack.Pop();
command.Execute();
_redoStack.Push(command);
}
e.Handled = true;
}
};
// 关联重做命令和Ctrl+Y快捷键
var redoCommand = new RedoCommand(textBox1);
var redoKey = new KeyEventArgs(Keys.Y | Keys.Control);
textBox1.KeyDown += (sender, e) =>
{
if (e.KeyCode == redoKey.KeyCode && e.Modifiers == redoKey.Modifiers)
{
if (_redoStack.Count > 0)
{
var command = _redoStack.Pop();
command.Execute();
_undoStack.Push(command);
}
e.Handled = true;
}
};
}
}
```
上面的代码中,我们定义了一个`ICommand`接口,包含了一个`Execute()`方法,表示该命令的执行操作。然后,我们定义了`UndoCommand`和`RedoCommand`类来分别实现撤销和重做操作。在`Form1`窗体中,我们将撤销和重做命令与`TextBox`控件的事件关联起来,当用户按下相应的快捷键或单击编辑器的撤销或重做按钮时,将调用相应的命令对象的`Execute()`方法。同时,我们还使用了两个`Stack`对象来实现撤销和重做操作的堆栈。
阅读全文