ninja star A Neat Way to Set the Cursor in WPF

by Michael Ceranski, posted on November 30 2012

I found this excellent post on stack overflow which uses a Stack to set and unset the cursor. Normally when you want to set the wait cursor in your application you would use a try/finally block to ensure that the cursor eventually gets set back to the original value:

Mouse.OverrideCursor = Cursors.Wait;
try {
    return Foo.Execute();
}
finally
{
    Mouse.OverrideCursor = null;
}

Don't get me wrong here...There is nothing wrong with using a try/finally. However, there is an alternative way to solve the same problem which I personally think is a more elegant and foolproof. So without further ado, here is the OverrideCursor class.

static Stack<Cursor> s_Stack = new Stack<Cursor>();

public OverrideCursor(Cursor changeToCursor) {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
        Mouse.OverrideCursor = changeToCursor;
}

public void Dispose() {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
        Mouse.OverrideCursor = cursor;
}

With the help of this class, we can ditch the try/finally and use this block of code instead:

using (new OverrideCursor(Cursors.Wait)) {
    return Foo.Execute();
}

So what is happening here? Well, in the OverrideCursor's constructor the current cursor is pushed on the stack and the cursor is updated to whatever you value you passed in as an argument. Later on when the object is Disposed the original cursor is fetched from the stack and restored. Since the code that launches my dialog is wrapped in a using statement the OverrideCursor instance will be disposed as soon as my form is displayed. Neat Trick!

Tags:
blog comments powered by Disqus

About the author

MikeMichael Ceranski is a developer specializing in the .NET stack. I have spent time as a DBA, Web Developer and even a network engineer. Up til now most of my career has revolved around the .NET stack but I have recently taken an interest in microcontrollers which has forced me to get acquainted with lower level languages such as C, and C++.

View my resume

Sponsors