Sunday, November 1, 2009

Defining and Raising Custom Events

We’ve all handled events before, e.g. the Load of a Form, the Click of a Button or the TextChanged of a TextBox. Many, even relatively experienced, developers aren’t too sure on how to raise events from their own classes though.

The .NET Framework provides a fairly simple mechanism for events but, more than that, a convention is used throughout the Framework for employing that mechanism. While you don’t have to, it’s a good idea to stick to that convention in your own code. Doing so means that your interface will be consistent with the rest of the Framework, and consistency is a good thing. Using your types will feel familiar to yourself and others because they will behave just like the types you’re used to using from the Framework.

First up, let’s define exactly what an event is. In conceptual terms, an event is a notification that something has happened. Just like your microwave oven makes a “beep” or “ding” sound to notify you that it has finished cooking your food, so a .NET object raises an event to notify any other objects that are listening that it has done something or something has been done to it.

Technically, an event is a member of a type, just like properties and methods, except its type is a delegate rather than a class or structure. A delegate, or at least an instance of a delegate, is an object that contains a reference to a method. In the case of an event, the method the delegate refers to is the event handler. As an example, the Button class has a Click event defined as type EventHandler. The EventHandler delegate is defined like so:

C#

public delegate void EventHandler(object sender, EventArgs e);

VB

Public Delegate Sub EventHandler(ByVal sender As Object, ByVal e As EventArgs)

That method signature should look familiar because it looks a lot like the signature of an event handler method, e.g.

C#

private void button1_Click(object sender, EventArgs e)
{
    // ...
}

VB

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    '...
End Sub

When you create a handler for the Click event of a Button in your form, what you’re actually doing is creating an instance of the EventHandler delegate, providing it a reference to your method and then assigning it to the Click member of the Button. When the Button is clicked, it goes to its Click event and invokes the delegate it finds there, which in turn invokes your method.

This post isn’t about delegates though, so if you want more information on their inner workings you should look for that elsewhere. This post is about defining and raising custom events, so let’s get on with that. The first thing we need is a class that will raise an event.

C#

public class Person
{
    private string _firstName;
    private string _lastName;
 
    public string FirstName
    {
        get
        {
            return this._firstName;
        }
        set
        {
            this._firstName = value;
        }
    }
 
    public string LastName
    {
        get
        {
            return this._lastName;
        }
        set
        {
            this._lastName = value;
        }
    }
}

VB

Public Class Person
 
    Private _firstName As String
    Private _lastName As String
 
    Public Property FirstName() As String
        Get
            Return Me._firstName
        End Get
        Set(ByVal value As String)
            Me._firstName = value
        End Set
    End Property
 
    Public Property LastName() As String
        Get
            Return Me._lastName
        End Get
        Set(ByVal value As String)
            Me._lastName = value
        End Set
    End Property
 
End Class

So, we have a class with two properties, which we can get and set. It might be convenient for us to receive a notification from an instance of this class when those property values change. For instance, if you are displaying the person’s name in some TextBoxes and the name gets changed in code, you’d want to know about it so that you could update the TextBoxes, right? For that we need an event to be raised when the property value changes.

The first thing to do is to declare the events as members in the Person class. Considering that these events are notifications of the FirstName and LastName property values being changed, it’s most appropriate that they be named “FirstNameChanged” and “LastNameChanged”, which is convention throughout the Framework.

C#

public event EventHandler FirstNameChanged;
public event EventHandler LastNameChanged;

VB

Public Event FirstNameChanged As EventHandler
Public Event LastNameChanged As EventHandler

Once the events are declared, you’ll find that the Person class now has events you can handle. That doesn’t do us any good if the events are never raised though, so let’s add some basic code to raise those events when the corresponding property values change.

C#

public string FirstName
{
    get
    {
        return this._firstName;
    }
    set
    {
        this._firstName = value;
 
        if (this.FirstNameChanged != null)
        {
            this.FirstNameChanged(this, EventArgs.Empty);
        }
    }
}
 
public string LastName
{
    get
    {
        return this._lastName;
    }
    set
    {
        this._lastName = value;
 
        if (this.LastNameChanged != null)
        {
            this.LastNameChanged(this, EventArgs.Empty);
        }
    }
}

VB

Public Property FirstName() As String
    Get
        Return Me._firstName
    End Get
    Set(ByVal value As String)
        Me._firstName = value
 
        RaiseEvent FirstNameChanged(Me, EventArgs.Empty)
    End Set
End Property
 
Public Property LastName() As String
    Get
        Return Me._lastName
    End Get
    Set(ByVal value As String)
        Me._lastName = value
 
        RaiseEvent LastNameChanged(Me, EventArgs.Empty)
    End Set
End Property

Note that, when the event is raised, the object passes itself as the first argument. The first argument is passed to the sender parameter, so the object is identifying itself as the sender, i.e. the object that raised the event.

The second argument is EventArgs.Empty, which is part of the standard pattern. You should be fairly used to your event handlers having a sender parameter of type Object and an e parameter of type EventArgs or something like it. The second parameter is the event’s data. The EventArgs class acts as a place-holder for events that don’t have any data and as a base class for the types used by events that do have data. Rather than create a new EventArgs object each time, we use the static/Shared Empty field, which returns an empty EventArgs object.

Now, the code we have will do the job but we can make it better. First of all, the event will be raised every time the corresponding property is set, whether the value actually changes or not. We should actually test the new value and only raise the event if it’s different to the old value.

C#

public string FirstName
{
    get
    {
        return this._firstName;
    }
    set
    {
        if (value != this._firstName)
        {
            this._firstName = value;
 
            if (this.FirstNameChanged != null)
            {
                this.FirstNameChanged(this, EventArgs.Empty);
            }
        }
    }
}
 
public string LastName
{
    get
    {
        return this._lastName;
    }
    set
    {
        if (value != this._lastName)
        {
            this._lastName = value;
 
            if (this.LastNameChanged != null)
            {
                this.LastNameChanged(this, EventArgs.Empty);
            }
        }
    }
}

VB

Public Property FirstName() As String
    Get
        Return Me._firstName
    End Get
    Set(ByVal value As String)
        If value <> Me._firstName Then
            Me._firstName = value
 
            RaiseEvent FirstNameChanged(Me, EventArgs.Empty)
        End If
    End Set
End Property
 
Public Property LastName() As String
    Get
        Return Me._lastName
    End Get
    Set(ByVal value As String)
        If value <> Me._lastName Then
            Me._lastName = value
 
            RaiseEvent LastNameChanged(Me, EventArgs.Empty)
        End If
    End Set
End Property

The next step is to implement the common pattern that is used throughout the Framework for raising events. That involves declaring a method whose purpose in life it is to raise the event.

C#

protected virtual void OnFirstNameChanged(EventArgs e)
{
    if (this.FirstNameChanged != null)
    {
        this.FirstNameChanged(this, e);
    }
}
 
protected virtual void OnLastNameChanged(EventArgs e)
{
    if (this.LastNameChanged != null)
    {
        this.LastNameChanged(this, e);
    }
}

VB

Protected Overridable Sub OnFirstNameChanged(ByVal e As EventArgs)
    RaiseEvent FirstNameChanged(Me, e)
End Sub
 
Protected Overridable Sub OnLastNameChanged(ByVal e As EventArgs)
    RaiseEvent LastNameChanged(Me, e)
End Sub

Such a method is used basically so that the event is only ever raised in one place. If you ever want to raise the event you simply call this method.

C#

public string FirstName
{
    get
    {
        return this._firstName;
    }
    set
    {
        if (value != this._firstName)
        {
            this._firstName = value;
            this.OnFirstNameChanged(EventArgs.Empty);
        }
    }
}
 
public string LastName
{
    get
    {
        return this._lastName;
    }
    set
    {
        if (value != this._lastName)
        {
            this._lastName = value;
            this.OnLastNameChanged(EventArgs.Empty);
        }
    }
}

VB

Public Property FirstName() As String
    Get
        Return Me._firstName
    End Get
    Set(ByVal value As String)
        If value <> Me._firstName Then
            Me._firstName = value
            Me.OnFirstNameChanged(EventArgs.Empty)
        End If
    End Set
End Property
 
Public Property LastName() As String
    Get
        Return Me._lastName
    End Get
    Set(ByVal value As String)
        If value <> Me._lastName Then
            Me._lastName = value
            Me.OnLastNameChanged(EventArgs.Empty)
        End If
    End Set
End Property

The primary advantage of this is linked to the way the method is declared. Notice that the methods above are declared protected/Protected and virtual/Overridable. This means that any derived classes can override these methods and change the type’s behaviour when the events are raised. The derived class simply calls the base implementation to raise the event, so code can be added before that call or after it to add new behaviour. This new behaviour will be invoked even if the method is called from the base class, such is the behaviour of overridden members. If the event was raised directly in the property setters of the base class then derived classes wouldn’t be able to add new behaviour because the properties are not declared virtual/Overridable.

It’s also worth noting that another part of the pattern is naming the method that raises an event the same as the event it raises, but with the “On” prefix added. Note that in .NET there is no OnLoad or OnClick event. The events are named Load and Click and the methods that raise them are name OnLoad and OnClick.

So, we now have a full, working implementation that follows the standard .NET pattern. We’ve declared the events, declared methods to raise them and then called those methods when the event notification is required. But wait; there’s more!

I said earlier that events may or may not have data associated with them. In the case of our FirstNameChanged and LastNameChanged events there is no data. Listeners are simply being notified that a property value has changed. If they want to know the new value they can simply get the property. As such an EventArgs object is used as a place-holder for the event handlers. Now let’s consider a situation where the event handlers will require some information that they cannot otherwise access themselves.

In that situation the object raising the event needs to pass that data to the event handler. It does this through the e parameter. In such cases the e parameter cannot be type EventArgs because the EventArgs class has no members that can store such data. As a result, we need to use a class that inherits EventArgs and then adds the required members. The Framework already contains numerous such class, e.g. MouseEventArgs and PaintEventArgs. You should use one of those existing classes if it’s appropriate to your event, otherwise you should define your own class.

For this example, let’s consider the situation where we want to notify listeners that the property value is going to change before it happens, in addition to notifying them that the property value has changed after it happens. If the property value hasn’t actually changed yet then there’s no way an event handler can get the new value, unless that data is passed to the event handler explicitly. For this we’ll define our own derived EventArgs class. We could define one for each event but they are both notifying about a String property changing so we can use the same class for both.

C#

public class StringPropertyChangingEventArgs : EventArgs
{
    private readonly string _proposedValue;
 
    public string ProposedValue
    {
        get
        {
            return this._proposedValue;
        }
    }
 
    public StringPropertyChangingEventArgs(string proposedValue)
    {
        this._proposedValue = proposedValue;
    }
}

VB

Public Class StringPropertyChangingEventArgs
    Inherits EventArgs
 
    Private ReadOnly _proposedValue As String
 
    Public ReadOnly Property ProposedValue() As String
        Get
            Return Me._proposedValue
        End Get
    End Property
 
    Public Sub New(ByVal proposedValue As String)
        Me._proposedValue = proposedValue
    End Sub
 
End Class

Note that the StringPropertyChangingEventArgs class inherits the EventArgs class and then adds a property for the new data we need: the proposed value of the property. There’s no need to include the current value of the property because the event handler can get that itself.

There are two more points to note here. The name of the class ends with “EventArgs”, which is part of the convention. Another is using the term “Changing” for an event related to a proposed change to a property value. This goes along with the convention of using “Changed” for an event related to a property that has changed already. For the events you would normally prefix the “Changing” with the name of the property. We can’t do that for this class though, because it’s to be used by more than one property/event.

Now that we have a type to pass the event data to the event handler, the next thing we need is an event. In the case of the FirstNameChanged and LastNameChanged events, we declared them as type EventHandler. That’s not possible for our FirstNameChanging and LastNameChanging events though because they will require a StringPropertyChangingEventArgs parameter rather than an EventArgs parameter, so their signatures will not match that of the EventHandler delegate. We need a different delegate. For this we have two choices. Firstly, we could define our own delegate with a signature that matches that of our event handlers. This is good practice if you’re exposing an event outside the current assembly. We’ll look at that option later but, if the event is only going to be used within the current project, it’s considered good practice to use the generic EventHandler(TEventArgs) delegate.

C#

public event EventHandler<StringPropertyChangingEventArgs> FirstNameChanging;
public event EventHandler<StringPropertyChangingEventArgs> LastNameChanging;

VB

Public Event FirstNameChanging As EventHandler(Of StringPropertyChangingEventArgs)
Public Event LastNameChanging As EventHandler(Of StringPropertyChangingEventArgs)

In this case the generic type of the delegate specifies the type of the second parameter of the event handler. Note that this type must be EventArgs or derived from EventArgs.

The next step is to declare methods to raise the events. They will be much as were those for the other events but with a different parameter type.

C#

protected virtual void OnFirstNameChanging(StringPropertyChangingEventArgs e)
{
    if (this.FirstNameChanging != null)
    {
        this.FirstNameChanging(this, e);
    }
}
 
protected virtual void OnLastNameChanging(StringPropertyChangingEventArgs e)
{
    if (this.LastNameChanging != null)
    {
        this.LastNameChanging(this, e);
    }
}

VB

Protected Overridable Sub OnFirstNameChanging(ByVal e As StringPropertyChangingEventArgs)
    RaiseEvent FirstNameChanging(Me, e)
End Sub
 
Protected Overridable Sub OnLastNameChanging(ByVal e As StringPropertyChangingEventArgs)
    RaiseEvent LastNameChanging(Me, e)
End Sub

All that remains is for us to call the methods to actually raise the events. Remember that these events are intended to notify our listeners that a property value is going to change, so they must be raised before the actual value changes.

C#

public string FirstName
{
    get
    {
        return this._firstName;
    }
    set
    {
        if (value != this._firstName)
        {
            this.OnFirstNameChanging(new StringPropertyChangingEventArgs(value));
            this._firstName = value;
            this.OnFirstNameChanged(EventArgs.Empty);
        }
    }
}
 
public string LastName
{
    get
    {
        return this._lastName;
    }
    set
    {
        if (value != this._lastName)
        {
            this.OnLastNameChanging(new StringPropertyChangingEventArgs(value));
            this._lastName = value;
            this.OnLastNameChanged(EventArgs.Empty);
        }
    }
}

VB

Public Property FirstName() As String
    Get
        Return Me._firstName
    End Get
    Set(ByVal value As String)
        If value <> Me._firstName Then
            Me.OnFirstNameChanging(New StringPropertyChangingEventArgs(value))
            Me._firstName = value
            Me.OnFirstNameChanged(EventArgs.Empty)
        End If
    End Set
End Property
 
Public Property LastName() As String
    Get
        Return Me._lastName
    End Get
    Set(ByVal value As String)
        If value <> Me._lastName Then
            Me.OnLastNameChanging(New StringPropertyChangingEventArgs(value))
            Me._lastName = value
            Me.OnLastNameChanged(EventArgs.Empty)
        End If
    End Set
End Property

That’s done but, really, what use is that event? It tells our listeners that the property value is about to change and what it’s about to change to, but to what use can that information be put? Normally, the reason you want to know that a property is about to change is so that you can abort the change if the value is unacceptable for some reason. That can’t be done in this case though, because the property value changes after the event has been handled no matter what.

The ability to cancel an action from an event handler already exists in the Framework. Consider the FormClosing event. You can ask the user for confirmation at that stage and, if they decide they don’t want to close the form, you simply set the e.Cancel property to True. This property is available because the e parameter is type CancelEventArgs. We can’t use CancelEventArgs for our methods though, because we need to provide the extra data consisting of the proposed property value. The solution is to have our StringPropertyChangingEventArgs class inherit CancelEventArgs instead of EventArgs. That way we get the Cancel property and we can add our own data to that.

C#

public class StringPropertyChangingEventArgs : CancelEventArgs
{
    private readonly string _proposedValue;
 
    public string ProposedValue
    {
        get
        {
            return this._proposedValue;
        }
    }
 
    public StringPropertyChangingEventArgs(string proposedValue)
    {
        this._proposedValue = proposedValue;
    }
}

VB

Public Class StringPropertyChangingEventArgs
    Inherits CancelEventArgs
 
    Private ReadOnly _proposedValue As String
 
    Public ReadOnly Property ProposedValue() As String
        Get
            Return Me._proposedValue
        End Get
    End Property
 
    Public Sub New(ByVal proposedValue As String)
        Me._proposedValue = proposedValue
    End Sub
 
End Class

The class name hasn’t changed so we don’t need to change any of the event and method declarations. We do, however, have to change the code in the property to handle the situation where the listener cancels the action. In that case the property value shouldn’t change.

C#

public string FirstName
{
    get
    {
        return this._firstName;
    }
    set
    {
        if (value != this._firstName)
        {
            StringPropertyChangingEventArgs e = new StringPropertyChangingEventArgs(value);
 
            this.OnFirstNameChanging(e);
 
            if (!e.Cancel)
            {
                this._firstName = value;
                this.OnFirstNameChanged(EventArgs.Empty);
            }
        }
    }
}
 
public string LastName
{
    get
    {
        return this._lastName;
    }
    set
    {
        if (value != this._lastName)
        {
            StringPropertyChangingEventArgs e = new StringPropertyChangingEventArgs(value);
 
            this.OnLastNameChanging(e);
 
            if (!e.Cancel)
            {
                this._lastName = value;
                this.OnLastNameChanged(EventArgs.Empty);
            }
        }
    }
}

VB

Public Property FirstName() As String
    Get
        Return Me._firstName
    End Get
    Set(ByVal value As String)
        If value <> Me._firstName Then
            Dim e As New StringPropertyChangingEventArgs(value)
 
            Me.OnFirstNameChanging(e)
 
            If Not e.Cancel Then
                Me._firstName = value
                Me.OnFirstNameChanged(EventArgs.Empty)
            End If
        End If
    End Set
End Property
 
Public Property LastName() As String
    Get
        Return Me._lastName
    End Get
    Set(ByVal value As String)
        If value <> Me._lastName Then
            Dim e As New StringPropertyChangingEventArgs(value)
 
            Me.OnLastNameChanging(e)
 
            If Not e.Cancel Then
                Me._lastName = value
                Me.OnLastNameChanged(EventArgs.Empty)
            End If
        End If
    End Set
End Property

This is as much as most people will usually need to do when it comes to custom events. There are a couple more points to consider though. As I said earlier, if your event is only going to be handled within your own project then it’s considered good practice to use the generic EventHandler(TEventArgs) delegate as your event’s type. If you’re exposing your event outside your assembly though, it’s considered good practice to declare your own delegate and declare your event as that type. This is in much the same vein as declaring properties that expose a collection. In that case, properties that will be accessible only within the assembly can use the generic List(T) class while, for properties exposed outside the assembly, you should declare your own custom collection type.

In this case we have two choices if we want to declare our own custom delegate. We can either declare a single delegate, just as we’ve declared a single EventArgs class, or declare a delegate for each event. Good practice dictates that we choose the latter.

C#

public delegate void FirstNameChangingEventHandler(object sender, StringPropertyChangingEventArgs e);
public delegate void LastNameChangingEventHandler(object sender, StringPropertyChangingEventArgs e);

VB

Public Delegate Sub FirstNameChangingEventHandler(ByVal sender As Object, ByVal e As StringPropertyChangingEventArgs)
Public Delegate Sub LastNameChangingEventHandler(ByVal sender As Object, ByVal e As StringPropertyChangingEventArgs)

Note that our delegates’ signatures match those of the methods that will be used to handle the events. Notice, also, that the names follow convention: the name of the event with an “EventHandler” suffix. Now we simply declare our events as these types instead of type Eventhandler(TEventArgs).

C#

public event FirstNameChangingEventHandler FirstNameChanging;
public event LastNameChangingEventHandler LastNameChanging;

VB

Public Event FirstNameChanging As FirstNameChangingEventHandler
Public Event LastNameChanging As LastNameChangingEventHandler

Finally, consider how our new cancellable event works. The caller sets the property and the appropriate “Changing” event is raised. The caller can either cancel the event, in which case the new property value is never committed and the corresponding “Changed” event is never raised, or else the event can be accepted, in which case the new property value is committed and the “Changed” event is raised.

That’s just what we want, but consider what happens if we have two event handlers for the same “Changing” event. Let’s say that the property is set and the “Changing” event is raised, invoking the first event handler. If e.Cancel is set to True in that event handler, what should happen? If the event has been cancelled then that should be the end of it, right? That’s not what will happen though. As it stands, all event handlers will be invoked no matter what. That means that the first event handler to get invoked might set e.Cancel to True, but then the second event handler can set it back to False again. That would mean that the property value change would be committed, even though it was cancelled by the first listener. It would depend on the circumstances but, more often than not, I would think that this would be undesirable behaviour.

To remedy this we need to create truly custom events, which means providing our own implementation to handle an event handler being added, an event handler being removed and the event being raised. The first step is to create a collection for our delegates so that we can loop through them and invoke each one individually rather than invoking them all as a group.

C#

private List<FirstNameChangingEventHandler> firstNameChangingHandlers = new List<FirstNameChangingEventHandler>();
private List<LastNameChangingEventHandler> lastNameChangingHandlers = new List<LastNameChangingEventHandler>();

VB

Private firstNameChangingHandlers As New List(Of FirstNameChangingEventHandler)
Private lastNameChangingHandlers As New List(Of LastNameChangingEventHandler)

Next we need to provide a custom implementation for our events that handles adding and removing event handlers.

C#

public event FirstNameChangingEventHandler FirstNameChanging
{
    add
    {
        this.firstNameChangingHandlers.Add(value);
    }
    remove
    {
        this.firstNameChangingHandlers.Remove(value);
    }
}
 
public event LastNameChangingEventHandler LastNameChanging
{
    add
    {
        this.lastNameChangingHandlers.Add(value);
    }
    remove
    {
        this.lastNameChangingHandlers.Remove(value);
    }
}

VB

Public Custom Event FirstNameChanging As FirstNameChangingEventHandler
    AddHandler(ByVal value As FirstNameChangingEventHandler)
        Me.firstNameChangingHandlers.Add(value)
    End AddHandler
 
    RemoveHandler(ByVal value As FirstNameChangingEventHandler)
        Me.firstNameChangingHandlers.Remove(value)
    End RemoveHandler
 
    RaiseEvent(ByVal sender As Object, ByVal e As StringPropertyChangingEventArgs)
        For Each handler As FirstNameChangingEventHandler In Me.firstNameChangingHandlers
            handler(sender, e)
            If e.Cancel Then Exit For
        Next
    End RaiseEvent
End Event
 
Public Custom Event LastNameChanging As LastNameChangingEventHandler
    AddHandler(ByVal value As LastNameChangingEventHandler)
        Me.lastNameChangingHandlers.Add(value)
    End AddHandler
 
    RemoveHandler(ByVal value As LastNameChangingEventHandler)
        Me.lastNameChangingHandlers.Remove(value)
    End RemoveHandler
 
    RaiseEvent(ByVal sender As Object, ByVal e As StringPropertyChangingEventArgs)
        For Each handler As LastNameChangingEventHandler In Me.lastNameChangingHandlers
            handler(sender, e)
            If e.Cancel Then Exit For
        Next
    End RaiseEvent
End Event

Notice that now, when a handler is added for the event, we store it in our own collection. We remove the handler from the collection when it’s removed from the event as well. In the case of VB, we also add extra code to control what happens when we call RaiseEvent. That allows the VB code that raises the event to remain unchanged, while the C# code that raises the event must provide the extra functionality for allowing the event to be cancelled before all event handlers have been executed.

C#

protected virtual void OnFirstNameChanging(StringPropertyChangingEventArgs e)
{
    foreach (FirstNameChangingEventHandler handler in this.firstNameChangingHandlers)
    {
        handler(this, e);
        if (e.Cancel) break;
    }
}
 
protected virtual void OnLastNameChanging(StringPropertyChangingEventArgs e)
{
    foreach (LastNameChangingEventHandler handler in this.lastNameChangingHandlers)
    {
        handler(this, e);
        if (e.Cancel) break;
    }
}

VB

Protected Overridable Sub OnFirstNameChanging(ByVal e As StringPropertyChangingEventArgs)
    RaiseEvent FirstNameChanging(Me, e)
End Sub
 
Protected Overridable Sub OnLastNameChanging(ByVal e As StringPropertyChangingEventArgs)
    RaiseEvent LastNameChanging(Me, e)
End Sub

In both cases, raising the event now consists of looping through the registered event handlers one by one. As soon as one of the event handlers cancels the event, no more event handlers are executed.

That’s everything. We’ve covered declaring our own events that have no data, defining our own custom EventArgs class, declaring events that use that custom class using the generic EventHandler(TEventArgs) delegate as well as our own custom delegates, passing data to the event handler and back again and, finally, defining custom events that provide their own implementation for adding and removing event handlers as well as raising the event itself. There’s now nothing you can’t do with events of your own. Here’s hoping you have an eventful future. ;-)

Sunday, October 18, 2009

Manipulating GDI+ Drawings

I've seen many people ask how to manipulate the drawing they produce using GDI+. This is no trivial thing because, as you'll know if you've used GDI+ much at all, your drawing is simply pixels on the screen. There are no objects that you can get references to, set properties on or call methods of.

If you want to use GDI+ to draw on your form and/or controls and you want to be able to change what's drawn at all then you really only have one course of action available. You need to declare one or more member variables, store data in those variables that describe your drawing and then read that data on the Paint event. If you want to be able manipulate your drawing, e.g. drag items around, then you need to use that same data to determine how the mouse state relates to your drawing and then make changes accordingly.

For this example, we're going to create a simple Windows Forms application that behaves, in a rudimentary way, like the VS design window. Just as you can draw controls onto a form, drag them around and use their right-click menu to change the z-order on a Windows Form, so our app will allow you to draw boxes by clicking and dragging, move boxes around by dragging and dropping and also to change the z-order using a right-click.

The app will draw white rectangles with a black border, which will make it easy to see which is in front of which. The boxes will have an apparent z-order, much as controls do on a form. We will add right-click functionality that will allow us to send a box to the back, making it appear to be behind the other boxes, or to bring it to the front, making it appear to be in front of all others. We will also add functionality to enable dragging and dropping boxes around the form.

So, first things first, you'll need to open VS and create a new Windows Forms Application project. I've tested this in VS 2008 but the code I'll provide should also work in VS 2005. I'll also provide both C# and VB code so you can use whichever language you like.

Let's start by adding a PictureBox to the form and setting its Dock property to Fill, so it fills the entire form. We're going to need handle some events of that PictureBox so let's create those event handlers now. We'll only consider the drawing part for now so what events will we need to handle? The user is going to depress the left mouse button to start drawing, drag the mouse to the opposite corner of the box they want to draw, then release the mouse button. To be able to pick up all of that activity we will need to handle the MouseDown, MouseMove and MouseUp events of the PictureBox. Of course, we're using GDI+ to draw on the PictureBox so we'll obviously need to handle its Paint event too.

As I said earlier, we need to store data that describes our drawing in one or more member variables that we can edit and then read in the Paint event handler. In this case we will need to store the start point and the end point of the box we're currently drawing. Two Point fields will do for that. We'll also need to store data for each box we'vew previously drawn. We'll use instances of the Rectangle structure to represent a box and we'll use a generic List to store a Rectangle for each box we've previosuly drawn.

C#

private Point startPoint;
private Point endPoint;
 
private List<Rectangle> boxes = new List<Rectangle>();

VB

Private startPoint As Point
Private endPoint As Point
 
Private boxes As New List(Of Rectangle)

First of all, let’s think about how we want the drawing done. That way we can implement the body of our Paint event handler and then essentially forget about it. So, all previously drawn boxes will be recorded as a Rectangle in our generic list while, if we are currently drawing a box, it will be defined by the start point and end point values.

C#

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
 
    foreach (Rectangle box in this.boxes)
    {
        g.FillRectangle(Brushes.White, box);
        g.DrawRectangle(Pens.Black, box);
    }
 
    if (Control.MouseButtons == MouseButtons.Left)
    {
        Rectangle box = this.GetRectangle(this.startPoint, this.endPoint);
 
        g.FillRectangle(Brushes.White, box);
        g.DrawRectangle(Pens.Black, box);
    }
}

VB

Private Sub PictureBox1_Paint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) Handles PictureBox1.Paint
    With e.Graphics
        For Each box As Rectangle In Me.boxes
            .FillRectangle(Brushes.White, box)
            .DrawRectangle(Pens.Black, box)
        Next
 
        If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
            Dim box As Rectangle = Me.GetRectangle(Me.startPoint, Me.endPoint)
 
            .FillRectangle(Brushes.White, box)
            .DrawRectangle(Pens.Black, box)
        End If
    End With
End Sub

Let’s look at a few points of interest in that code. First, it uses a foreach/For Each loop to enumerate the existing boxes for drawing. As such it will draw the oldest first, thus placing newer boxes in front of older, which is the desired behaviour. If there is a box currently being drawn it gets drawn last of all, in front of all other boxes. Note that the test for whether or not a box is currently being drawn is that the left mouse button and only the left mouse button is depressed. Finally, note that that code calls a GetRectangle method that takes two Point arguments and returns a Rectangle. It’s our next job to write that method.

So, if you’re given two Points, how will you create a Rectangle from them? To create a Rectangle we need the coordinates of the top, left corner and the dimensions. We’ll obviously assume that our two Points are diagonally opposite but we don’t which diagonal or in which order. We don’t have to care though. We know that, whatever combination of corners we have, the top, left corner will be defined by the lower of the two X values and the lower of the two Y values. The dimensions will just be the difference between the X values and the Y values, although we’ll have to take the absolute value to allow for either order.

C#

private Rectangle GetRectangle(Point startPoint, Point endPoint)
{
    return new Rectangle(Math.Min(startPoint.X, endPoint.X),
                         Math.Min(startPoint.Y, endPoint.Y),
                         Math.Abs(startPoint.X - endPoint.X),
                         Math.Abs(startPoint.Y - endPoint.Y));
}

VB

Private Function GetRectangle(ByVal startPoint As Point, _
                              ByVal endPoint As Point) As Rectangle
    Return New Rectangle(Math.Min(startPoint.X, endPoint.X), _
                         Math.Min(startPoint.Y, endPoint.Y), _
                         Math.Abs(startPoint.X - endPoint.X), _
                         Math.Abs(startPoint.Y - endPoint.Y))
End Function

Next we need to look at what we’re going to do when the user depresses the mouse button. That location will become the start point for the new box, and it will also be the initial value for the end point, given that the mouse hasn’t moved from the start point yet.

C#

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (Control.MouseButtons == MouseButtons.Left)
    {
        Point location = e.Location;
 
        this.startPoint = location;
        this.endPoint = location;
    }
}

VB

Private Sub PictureBox1_MouseDown(ByVal sender As Object, _
                                  ByVal e As MouseEventArgs) Handles PictureBox1.MouseDown
    If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
        Dim location As Point = e.Location
 
        Me.startPoint = location
        Me.endPoint = location
    End If
End Sub

Note that the value tested is Control.MouseButtons rather than e.Button. This because we want to start drawing if the left mouse button and only the left button is depressed. If the user has already depressed the right mouse button and then depresses the left, e.Button would still have the value Left, while Control.MouseButtons would not.

Next, let’s consider what we want to do when the user releases the mouse button. Let’s keep it simple to begin with. We first need to create a Rectangle from the start point and end point. We can do that courtesy of our GetRectangle method. We then need to add that to our List of Rectangles so that it gets drawn. Finally, we need to invalidate the area occupied by that Rectagle and then tell the PictureBox to repaint it. We invalidate only the area that has changed, for efficiency.

C#

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left &&
        Control.MouseButtons == MouseButtons.None)
    {
        this.endPoint = e.Location;
 
        Rectangle box = this.GetRectangle(this.startPoint, this.endPoint);
 
        this.boxes.Add(box);
        this.pictureBox1.Invalidate(box);
        this.pictureBox1.Update();
    }
}

VB

Private Sub PictureBox1_MouseUp(ByVal sender As Object, _
                                ByVal e As MouseEventArgs) Handles PictureBox1.MouseUp
    If e.Button = Windows.Forms.MouseButtons.Left AndAlso _
       Control.MouseButtons = Windows.Forms.MouseButtons.None Then
        Me.endPoint = e.Location
 
        Dim box As Rectangle = Me.GetRectangle(Me.startPoint, Me.endPoint)
 
        Me.boxes.Add(box)
        Me.PictureBox1.Invalidate(box)
        Me.PictureBox1.Update()
    End If
End Sub

We’re actually at the point where our application can do something useful, so let’s give it a try. Run your project and try creating a few boxes. Just push the left mouse button, drag the mouse and then release. You’ll see that nothing gets drawn while we’re dragging yet, but a box appears when we release the mouse.

There’s a bit of a problem though. Notice that the black border only gets drawn on the top and left sides, not on the right and bottom. That’s actually not an issue with the drawing itself but rather an issue with the invalidation. When you call Invalidate and pass a Rectangle, the right and bottom edges are exclusive. As such, if we want that last row and column of pixels to be drawn when we call Update, we need to enlarge the area we invalidate at least one pixel further right and one pixel further down. This is something that we’ll need to do again so let’s put it into its own method.

C#

private void InvalidateRectangle(Rectangle box)
{
    box.Inflate(1, 1);
    this.pictureBox1.Invalidate(box);
}

VB

Private Sub InvalidateRectangle(ByVal box As Rectangle)
    box.Inflate(1, 1)
    Me.PictureBox1.Invalidate(box)
End Sub

The Inflate method will increase the width and the height of the Rectangle by the specified amounts in both directions. As such, we’ll end up invalidating one row of pixels above and one column of pixels to the left that haven’t actually changed. That’s only a small number though and this code is more succinct than what we would write to get the size increase just to the right and down. It’s not a big deal though so, by all means, write that extra bit of code if want to be as efficient as possible. Note also that it’s safe to inflate the parameter directly because it’s just a copy of the Rectangle in the List, owing to Rectangle being a value type.

We can now call our InvalidateRectangle method from our MouseUp event handler.

C#

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left &&
        Control.MouseButtons == MouseButtons.None)
    {
        this.endPoint = e.Location;
 
        Rectangle box = this.GetRectangle(this.startPoint, this.endPoint);
 
        this.boxes.Add(box);
        this.InvalidateRectangle(box);
        this.pictureBox1.Update();
    }
}

VB

Private Sub PictureBox1_MouseUp(ByVal sender As Object, _
                                ByVal e As MouseEventArgs) Handles PictureBox1.MouseUp
    If e.Button = Windows.Forms.MouseButtons.Left AndAlso _
       Control.MouseButtons = Windows.Forms.MouseButtons.None Then
        Me.endPoint = e.Location
 
        Dim box As Rectangle = Me.GetRectangle(Me.startPoint, Me.endPoint)
 
        Me.boxes.Add(box)
        Me.InvalidateRectangle(box)
        Me.PictureBox1.Update()
    End If
End Sub

Now let’s try running our project again. This time notice that the black border is drawn on all four sides. Try drawing boxes from using both diagonals in both directions and you’ll see it works correctly for all four cases. Also notice that new boxes are drawn in front of old ones.

The next order of business is getting the boxes to draw as we drag the mouse, rather than just appearing when we release the mouse button. For that to happen we need to tell the PictureBox to repaint from the MouseMove event handler. In this case we want to, again, check that the left mouse button and only the left mouse button is depressed. We’ll need to invalidate the area previously occupied by the box being drawn, in case it has shrunk, then invalidate the new area occupied by the box, then force a repaint.

C#

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (Control.MouseButtons == MouseButtons.Left)
    {
        this.InvalidateRectangle(this.GetRectangle(this.startPoint,
                                                   this.endPoint));
        this.endPoint = e.Location;
        this.InvalidateRectangle(this.GetRectangle(this.startPoint,
                                                   this.endPoint));
        this.pictureBox1.Update();
    }
}

VB

Private Sub PictureBox1_MouseMove(ByVal sender As Object, _
                                  ByVal e As MouseEventArgs) Handles PictureBox1.MouseMove
    If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
        Me.InvalidateRectangle(Me.GetRectangle(Me.startPoint, Me.endPoint))
        Me.endPoint = e.Location
        Me.InvalidateRectangle(Me.GetRectangle(Me.startPoint, Me.endPoint))
        Me.PictureBox1.Update()
    End If
End Sub

Try running the project and drawing some boxes again. You’ll see that now the box gets drawn on the form as we’re dragging the mouse. Try dragging the mouse in a circle around the start point and see how it gets drawn correctly in all four directions. Try doing the same when drawing a box over some others and see how those underneath get redrawn correctly as they reappear, thanks to our invalidating the old area of the box as well as the new.

That’s the end of the first stage of the project: drawing the boxes. The next stage is to be able to right-click a box and select an option to send it to the back of the z-order or bring it to the front. In order to do that, we’re obviously going to have to add a ContextMenuStrip to the form. We won’t be able to just assign it to the PictureBox’s ContextMenuStrip property though, because we’ll only want to show it when the user right-clicks on a box.

Go ahead and add a ContextMenuStrip to your form. Add two items to the menu with text “Bring to Front” and “Send to Back”. You might as well create handlers for their Click events now, although we won’t add any code to them just yet. Before we do that we need to add a handler for the PictureBox’s MouseClick event, to detect tight-clicks. In order to determine whether the mouse pointer was in a box when the right-click occurred, we will need to loop through our List of Rectangles and check whether each one contains the mouse pointer. This is something we’ll have to do again so let’s put it into its own method.

C#

private int GetRectangleIndexAtPoint(Point location)
{
    Rectangle box;
    int result = -1;
 
    for (int index = this.boxes.Count - 1; index >= 0; index--)
    {
        box = this.boxes[index];
 
        if (box.Contains(location))
        {
            result = index;
            break;
        }
    }
 
    return result;
}

VB

Private Function GetRectangleIndexAtPoint(ByVal location As Point) As Integer
    Dim box As Rectangle
    Dim result As Integer = -1
 
    For index As Integer = Me.boxes.Count - 1 To 0 Step -1
        box = Me.boxes(index)
 
        If box.Contains(location) Then
            result = index
            Exit For
        End If
    Next
 
    Return result
End Function

Notice that that code loops through the List backwards. That’s because, if two boxes overlap, we want to detect the front-most one, which will have a higher index.

Now let’s use that method to detect whether or not we should display the ContextMenuStrip on a right-click.

C#

private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right &&
        Control.MouseButtons == MouseButtons.None)
    {
        Point location = e.Location;
 
        this.selectedBoxIndex = this.GetRectangleIndexAtPoint(location);
 
        if (this.selectedBoxIndex != -1)
        {
            this.contextMenuStrip1.Show(this.pictureBox1, location);
        }
    }
}

VB

Private Sub PictureBox1_MouseClick(ByVal sender As Object, _
                                   ByVal e As MouseEventArgs) Handles PictureBox1.MouseClick
    If e.Button = Windows.Forms.MouseButtons.Right AndAlso _
       Control.MouseButtons = Windows.Forms.MouseButtons.None Then
        Dim location As Point = e.Location
 
        Me.selectedBoxIndex = Me.GetRectangleIndexAtPoint(location)
 
        If Me.selectedBoxIndex <> -1 Then
            Me.ContextMenuStrip1.Show(Me.PictureBox1, location)
        End If
    End If
End Sub

Notice that the result of the GetRectangleIndexAtPoint method is assigned to a field that we are yet to declare.

C#

private int selectedBoxIndex;

VB

Private selectedBoxIndex As Integer

That field is required because we’ll need to its value in order to identify which box to manipulate when the user selects a menu item.

The code first checks that the right mouse button was released and there are no other buttons currently depressed. In that case it gets the index of the front-most box that contains the mouse pointer. If there is such a box the menu is displayed at the mouse pointer location.

Now it’s time to implement the actions associated with the menu items. If you haven’t already, you should add Click event handlers for both menu items now. In each case we will want to move the box that was right-clicked, which is identified by the selectedBoxIndex field, from its current position to one end or the other. If we’re bringing the box to the front then it needs to be drawn last, so it should be placed at the end of the List, while if we’re sending it to the back it should be at the beginning of the List, to get drawn first.

C#

private void bringToFrontToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.ChangeRectangleIndex(this.selectedBoxIndex, this.boxes.Count);
}
 
private void sendToBackToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.ChangeRectangleIndex(this.selectedBoxIndex, 0);
}
 
private void ChangeRectangleIndex(int oldIndex, int newIndex)
{
    Rectangle box = this.boxes[oldIndex];
 
    if (oldIndex < newIndex)
    {
        newIndex--;
    }
 
    this.boxes.RemoveAt(oldIndex);
    this.boxes.Insert(newIndex, box);
 
    this.InvalidateRectangle(box);
    this.pictureBox1.Update();
}

VB

Private Sub BringToFrontToolStripMenuItem_Click(ByVal sender As Object, _
                                                ByVal e As EventArgs) Handles BringToFrontToolStripMenuItem.Click
    Me.ChangeRectangleIndex(Me.selectedBoxIndex, Me.boxes.Count)
End Sub
 
Private Sub SendToBackToolStripMenuItem_Click(ByVal sender As Object, _
                                              ByVal e As EventArgs) Handles SendToBackToolStripMenuItem.Click
    Me.ChangeRectangleIndex(Me.selectedBoxIndex, 0)
End Sub
 
Private Sub ChangeRectangleIndex(ByVal oldIndex As Integer, ByVal newIndex As Integer)
    Dim box As Rectangle = Me.boxes(oldIndex)
 
    If oldIndex < newIndex Then
        newIndex -= 1
    End If
 
    Me.boxes.RemoveAt(oldIndex)
    Me.boxes.Insert(newIndex, box)
 
    Me.InvalidateRectangle(box)
    Me.PictureBox1.Update()
End Sub

While it would be possible for the bring-to-front functionality to use Add instead of Insert, I’ve used Insert in both cases for the sake of code reuse. The ChangeRectangleIndex function first gets the box that selected by the right-click. It then adjusts the new index if necessary, because removing an item will decrement the index of all subsequent items. The box is then removed from the list and re-inserted at the new index. Finally, the area occupied by the box in question is invalidated and a repaint is forced.

Try running the project again and drawing a few boxes. Now try right-clicking in various places, some on a box and some not. You’ll see that the menu is only displayed when the click is on a box, as it should be. Now try selecting the two menu options and see the apparent z-order of the boxes change accordingly. Also note that, if you right-click on an area where two boxes overlap, it’s always the one in front that receives the command from the menu item.

OK, that’s the setup over. Now let’s get down to the business at hand: implementing drag-and-drop functionality for our boxes. First of all, let’s add a ToolStrip to our form and then add one button. That button will be used for switching our app from drawing mode to dragging mode. Set the Text of the button to “Click to Drag” and set its DisplayStyle to “Text”. Now, at this point you’ll want to right-click on your PictureBox and select “Bring to Front”, to prevent it filling the entire form and going behind the ToolStrip. Finally, double-click the button to create a handler for its Click event. We now want to add a flag that will indicate to the app whether it is in drawing mode or dragging mode and have that flag toggled when the tool bar button is clicked.

C#

private bool drawMode = true;
 
private void toolStripButton1_Click(object sender, EventArgs e)
{
    this.drawMode = !this.drawMode;
 
    if (this.drawMode)
    {
        this.toolStripButton1.Text = "Click to Drag";
    }
    else
    {
        this.toolStripButton1.Text = "Click to Draw";
    }
}

VB

Private drawMode As Boolean = True
 
Private Sub ToolStripButton1_Click(ByVal sender As Object, _
                                   ByVal e As EventArgs) Handles ToolStripButton1.Click
    Me.drawMode = Not Me.drawMode
 
    If Me.drawMode Then
        Me.ToolStripButton1.Text = "Click to Drag"
    Else
        Me.ToolStripButton1.Text = "Click to Draw"
    End If
End Sub

Note that the flag is true by default, indicating that we are in draw mode to begin with. The text displayed on the button indicates what the next click will do, which is why we set the Text to “Click to Drag” in the designer.

At the moment, all the PictureBox’s event handlers assume that we are drawing a new box if the left mouse button is depressed. We’re going to have to go through all of them and change that behaviour so that the code will only draw a new box if we are in draw mode. In drag mode something new will happen.

Let’s start with the Paint event handler. At the moment the code is drawing all the boxes in the list and then, if the left mouse button is down, it draws the new box. Now, we will only want to draw the new box if the left mouse button is down AND we are in draw mode.

C#

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
 
    foreach (Rectangle box in this.boxes)
    {
        g.FillRectangle(Brushes.White, box);
        g.DrawRectangle(Pens.Black, box);
    }
 
    if (this.drawMode && Control.MouseButtons == MouseButtons.Left)
    {
        Rectangle box = this.GetRectangle(this.startPoint, this.endPoint);
 
        g.FillRectangle(Brushes.White, box);
        g.DrawRectangle(Pens.Black, box);
    }
}

VB

Private Sub PictureBox1_Paint(ByVal sender As Object, _
                              ByVal e As PaintEventArgs) Handles PictureBox1.Paint
    With e.Graphics
        For Each box As Rectangle In Me.boxes
            .FillRectangle(Brushes.White, box)
            .DrawRectangle(Pens.Black, box)
        Next
 
        If Me.drawMode AndAlso _
           Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
            Dim box As Rectangle = Me.GetRectangle(Me.startPoint, Me.endPoint)
 
            .FillRectangle(Brushes.White, box)
            .DrawRectangle(Pens.Black, box)
        End If
    End With
End Sub

Next, let’s look at the MouseDown event. At the moment the code will store the drawing start point and the current drawing end point. If we’re dragging we are still going to want to remember the start point because we need to know where we’re dragging from, but the end point isn’t really relevant. What will need to remember though is which box, if any, we are dragging.

C#

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (Control.MouseButtons == MouseButtons.Left)
    {
        Point location = e.Location;
 
        this.startPoint = location;
 
        if (this.drawMode)
        {
            this.endPoint = location;
        }
        else
        {
            this.selectedBoxIndex = this.GetRectangleIndexAtPoint(location);
        }
    }
}

VB

Private Sub PictureBox1_MouseDown(ByVal sender As Object, _
                                  ByVal e As MouseEventArgs) Handles PictureBox1.MouseDown
    If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
        Dim location As Point = e.Location
 
        Me.startPoint = location
 
        If Me.drawMode Then
            Me.endPoint = location
        Else
            Me.selectedBoxIndex = Me.GetRectangleIndexAtPoint(location)
        End If
    End If
End Sub

When the mouse moves, we need to determine whether we’re dragging a box and, if we are, how far we’ve dragged it. We then need to move the box that distance and set the current location as the new starting point for the next drag. Because the box will have moved we need to tell the PictureBox to repaint. We’ll need to invalidate the area the box occupied before the move and the area it occupies afterwards.

C#

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (Control.MouseButtons == MouseButtons.Left)
    {
        if (this.drawMode)
        {
            this.InvalidateRectangle(this.GetRectangle(this.startPoint,
                                                       this.endPoint));
            this.endPoint = e.Location;
            this.InvalidateRectangle(this.GetRectangle(this.startPoint,
                                                       this.endPoint));
            this.pictureBox1.Update();
        }
        else if (this.selectedBoxIndex != -1)
        {
            Rectangle box = this.boxes[this.selectedBoxIndex];
            Point location = e.Location;
 
            this.InvalidateRectangle(box);
 
            box.Offset(location.X - this.startPoint.X,
                       location.Y - this.startPoint.Y);
            this.boxes[this.selectedBoxIndex] = box;
            this.startPoint = location;
 
            this.InvalidateRectangle(box);
            this.pictureBox1.Update();
        }
    }
}

VB

Private Sub PictureBox1_MouseMove(ByVal sender As Object, _
                                  ByVal e As MouseEventArgs) Handles PictureBox1.MouseMove
    If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
        If Me.drawMode Then
            Me.InvalidateRectangle(Me.GetRectangle(Me.startPoint, Me.endPoint))
            Me.endPoint = e.Location
            Me.InvalidateRectangle(Me.GetRectangle(Me.startPoint, Me.endPoint))
            Me.PictureBox1.Update()
        ElseIf Me.selectedBoxIndex <> -1 Then
            Dim box As Rectangle = Me.boxes(Me.selectedBoxIndex)
            Dim location As Point = e.Location
 
            Me.InvalidateRectangle(box)
 
            box.Offset(location.X - Me.startPoint.X, _
                       location.Y - Me.startPoint.Y)
            Me.boxes(Me.selectedBoxIndex) = box
            Me.startPoint = location
 
            Me.InvalidateRectangle(box)
            Me.PictureBox1.Update()
        End If
    End If
End Sub

Notice that, after offsetting the box the distance that the mouse pointer has moved, the box is assigned box to the List item. That’s because, again, Rectangle is a value type so the code retrieves and edits a copy of the Rectangle in the list. After making changes we must overwrite the original with that copy so the changes are persisted.

Nothing needs to happen on the MouseUp event when dragging so the only change we need to make to that handler is a check for draw mode.

C#

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (this.drawMode &&
        e.Button == MouseButtons.Left &&
        Control.MouseButtons == MouseButtons.None)
    {
        this.endPoint = e.Location;
 
        Rectangle box = this.GetRectangle(this.startPoint, this.endPoint);
 
        this.boxes.Add(box);
        this.InvalidateRectangle(box);
        this.pictureBox1.Update();
    }
}

VB

Private Sub PictureBox1_MouseUp(ByVal sender As Object, _
                            ByVal e As MouseEventArgs) Handles PictureBox1.MouseUp
    If Me.drawMode AndAlso _
       e.Button = Windows.Forms.MouseButtons.Left AndAlso _
       Control.MouseButtons = Windows.Forms.MouseButtons.None Then
        Me.endPoint = e.Location
 
        Dim box As Rectangle = Me.GetRectangle(Me.startPoint, Me.endPoint)
 
        Me.boxes.Add(box)
        Me.InvalidateRectangle(box)
        Me.PictureBox1.Update()
    End If
End Sub

Believe it or not, that’s it! Run the project and draw a few boxes, as you did before, and then click the button on the tool bar to switch to drag mode. Try clicking and dragging in some empty space and notice that no new box gets drawn. Now try clicking and dragging on a box and notice that the box follows the mouse pointer. You should also note that the z-order is always maintained during drag operations. You can still use the context menu to change the z-order while in drag mode so you might like to play around with that to confirm that it works with dragging too. If you want to draw a few more boxes then just click the tool button again to switch back to draw mode.

So, that’s all there is to it. There may not be any actual objects on-screen to manipulate directly, but there are always objects. With GDI+ we must have data stored somewhere that represents the drawing in some way, so we can simply manipulate those objects appropriately and force the UI to repaint to see the new drawing. We just need to do a little bit more work to calculate where we are and what we’re moving. We’re developers though: we love that stuff!