.NET Zone is brought to you in partnership with:

Michael Ceranski is a .NET developer from Buffalo NY. He has been writing code for over 10 years starting with Borland Delphi and later migrating to the .NET stack. Michael enjoys blogging about .NET, MVC and jQuery. When Michael is not consulting he spends his time working on WeBlog, a next generation blogging platform written in ASP.NET MVC 2. Michael is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

A Neat Way to Set the Cursor in WPF

12.05.2012
| 5666 views |
  • submit to reddit

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 BillOfMaterialListView.Execute(keyword, autoSearch);
}

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!

Published at DZone with permission of Michael Ceranski, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)