Using VS - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Using VS arrow Implementing a Graphics Undo Command with the Stack Class
Implementing a Graphics Undo Command with the Stack Class
By Peter Aitken

Rate This Article: Add This Article To:

Make it possible for your application's users to say "Oops!" With the .NET framework, it's not that hard to include an Undo feature in your programs.

Almost every commercial program for manipulating data implements some sort of an "undo" command. It's a real safety blanket for users—I know it is for me! I can make any change I want to the document, secure in the knowledge that I can reverse the change and revert to the previous version with the tap of a key. If you develop applications that let users edit data, you should consider including an undo feature. With the .NET framework, it's not all that difficult.

How Does Undo Work?

ADVERTISEMENT

There are various methods for implementing a undo command in your program. The easiest method, and the one I'll demonstrate later, is simply to keep a copy of the old version of the data each time the user makes a change. Then, the undo action need only discard the new, changed data and restore the saved version. By keeping multiple copies you can have a multi-level undo, letting the user move back a step at a time by undoing several editing actions.

This method of implementing Undo works if the data being manipulated — the document, in other words — is in a self-contained form that lends itself to easy saving and restoring. In .NET this would of course be an object, which is how you should encapsulate your data whenever possible in any event. Note that undo data is almost always saved to memory rather than disk to permit fast restores. One disadvantage of this method is that, for large documents, saving a few undo copies can take up a significant amount of memory.

The Stack Class

The stack is a data storage algorithm that has been around at least since the days of vacuum tubes. It works on a last in, first out basis. When you put data items on a stack, a processing known as pushing, they are stored in order. When you retrieve items, know as popping, they come off in reverse order. Suppose you push the value 7, then push the value 12, and finally push the value 5. If you then did three pops, the items would be retrieved in the order 5 first, then 12, and then 7. Stacks are very useful in many programming situations.

The .NET framework has a Stack class that implements a stack algorithm. Even better, the data items that this class stores are type Object, providing great flexibility. There are five class members you need to know about:

  • Push: puts an object on the stack.
  • Pop: retrieves the top object from the stack.
  • Peek: returns the top object on the stack without removing it.
  • Count: returns the number of objects on the stack.
  • Clear: removes all items from the stack.

If you try to pop an object off an empty stack, an InvalidOperationException is thrown. Your program should always catch this exception when popping (or verify that Count is >= 1 before calling the Pop method).

A Stack object places no limits on the number of items stored; if you want to impose such a limit, you can do so in code or by defining a class that inherits from Stack and includes a capacity limit. When using the Stack class for undo, you may want to impose a limit to avoid placing too much demand on memory resources. When the limit is reached, the bottom (oldest) item on the stack should be deleted to make room for the new item being placed on the top.

Graphics Undo

Now we have all the pieces in place and can look at the details of implementing an undo command in a graphics program. Given the tools that .NET provides it is surprisingly easy. The details may differ slightly based on your project, but the following steps should be applicable to almost any project. This example assumes that your graphics program is using a Bitmap object to hold the graphic image that is being edited.

First, add an Edit menu to the main form's menu (if it does not already have one), and add an Undo command to the Edit menu. This is the traditional location of the undo command in Windows programs. The traditional keyboard shortcut is Ctrl+Z; you can add that to the command as well if you like.

Next, add a declaration of type Stack to the program's main form at the class level:

Stack UndoBuffer;

In the form's Load() event procedure, add the following code to instantiate the Undo buffer:

UndoBuffer = new Stack();

The next bit of code performs the action of saving an undo copy whenever the graphic is changed. The location of this code depends on your program and on what you want to consider a "change." Place this code where it will be executed whenever you want an undo copy created. This code assumes that the bitmap that is being edited is named bmp:

Bitmap undo =(Bitmap)bmp.Clone();
UndoBuffer.Push(undo);

The next step enables the Edit|Undo menu command if an Undo is available, and disables it if not. Create a Select() event procedure for the Edit menu and add this code (replace MenuItemName with the name of the Undo item on the Edit menu)

if (UndoBuffer.Count > 0)
    MenuItemName.Enabled = true;
else
    MenuItemName.Enabled = false;

Create a Click() event procedure for the Undo menu command and add the following code to it. calling the Refresh() method ensures that the screen displays the "undone" image.

bmp = (Bitmap)UndoBuffer.Pop();
this.Refresh();

Finally, you clear the undo buffer whenever a new file is created or loaded:

UndoBuffer.Clear();

If your program permits multiple images to be open for editing at the same time, you'll need to implement Undo for each of them. The easiest way to do this is to define a wrapper class for the Bitmap class, including the necessary undo and restore code in your class. The basic programming remains the same as I described here.




Discuss Implementing a Graphics Undo Command with the Stack Class
 
>>> Be the FIRST to comment on this article!
 

 
 
>>> More Using VS Articles          >>> More By Peter Aitken
 



Top Technology Pros One-to-one

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.