A Neat Way to Set the Cursor in WPF
Join the DZone community and get the full member experience.
Join For FreeI 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, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments