我正在尝试将命令模式应用于具有撤销功能的简单绘画应用程序中。但是,我在撤销操作的OnPaint
事件上遇到了问题。以下是代码:
[已解决] 详见帖子末尾
interface ICommand {
void Execute();
void UnExecute();
}
class DrawLineCommand : ICommand {
private SimpleImage simpleImage;
private Image prevImage;
public DrawLineCommand(SimpleImage simpleImage) {
this.simpleImage = simpleImage;
this.prevImage = simpleImage.Image;
}
public void Execute() {
simpleImage.DrawLine();
}
public void UnExecute() {
simpleImage.Image = prevImage;
}
}
class CommandManager {
private Stack undoStack = new Stack();
public void ExecuteCommand(ICommand command) {
command.Execute();
undoStack.Push(command);
}
public void UnExecuteCommand() {
if (undoStack.Count > 0) {
ICommand command = (ICommand)undoStack.Pop();
command.UnExecute();
}
}
}
class SimpleImage {
private Point startPoint;
private Point endPoint;
private PictureBox pictureBox;
public SimpleImage(PictureBox pictureBox) {
this.pictureBox = pictureBox;
pictureBox.Paint += new PaintEventHandler(pictureBox_Paint);
}
void pictureBox_Paint(object sender, PaintEventArgs e) {
// this code shows the line during drawing
// this code is under "if operation == drawLine" block
Graphics graphics = e.Graphics;
graphics.DrawLine(Pens.Red, startPoint, endPoint);
// how can i refresh picturebox after undo operation?
// "if operation == undo" then ??
}
public void DrawLine() {
// this code actually saves finally drawn line
Image img = Image;
Graphics graphics = Graphics.FromImage(img);
graphics.DrawLine(Pens.Red, startPoint, endPoint);
Image = img;
}
public void Invalidate() {
pictureBox.Invalidate();
}
public Image Image {
get { return pictureBox.Image; }
set { pictureBox.Image = value; }
}
public Point StartPoint {
get { return startPoint; }
set { startPoint = value; }
}
public Point EndPoint {
get { return endPoint; }
set { endPoint = value; }
}
}
public partial class FormMain : Form {
private PictureBox pictureBox;
private SimpleImage simpleImage;
private CommandManager commandManager;
public FormMain() {
InitializeComponent();
simpleImage = new SimpleImage(this.pictureBox);
commandManager = new CommandManager();
}
void pictureBox_MouseDown(object sender, MouseEventArgs e) {
if (e.Button != MouseButtons.Left)
return;
simpleImage.StartPoint = e.Location;
}
void pictureBox_MouseMove(object sender, MouseEventArgs e) {
if (e.Button != MouseButtons.Left)
return;
simpleImage.EndPoint = e.Location;
simpleImage.Invalidate();
}
void pictureBox_MouseUp(object sender, MouseEventArgs e) {
simpleImage.Invalidate();
commandManager.ExecuteCommand(new DrawLineCommand(simpleImage));
}
}
实际上,它画了一条线,执行命令并将其推入堆栈。我无法实现工作中的UNDO。我的意思是,逐步调试时,我看到对象从堆栈中弹出,然后执行OnPaint。但是实际上没有显示“先前”的图像。
我已经阅读了许多网站,并且还从其中一个codeproject网站/文章中获得了示例应用程序。它像狗一样工作。唯一的区别是这种残忍的OnPaint方法。
提前感谢任何建议!
[编辑]匆忙之中,我忘记了将一个引用类型分配给另一个不是复制它(创建独立对象),更改如下:
this.prevImage = simpleImage.Image;
在少数地方解决了问题。现在一切都正常运作。