On several of my usercontrols, I change the cursor by using
this.Cursor = Cursors.Wait;
when I click on something.
Now I want to do the same thing on a WPF page on a button click. When I hover over my button, the cursor changes to a hand, but when I click it, it doesn't change to the wait cursor. I wonder if this has something to do with the fact that it's a button, or because this is a page and not a usercontrol? This seems like weird behavior.
A switch statement filters on the cursor name and sets the Cursor property on the Border which is named DisplayArea. If the cursor change is set to "Entire Application", the OverrideCursor property is set to the Cursor property of the Border control. This forces the cursor to change for the whole application.
Cursor class. Create an instance of Cursor using the new operator and pass the cursor type to the Cursor class constructor. We can change Swing's objects ( JLabel , JTextArea , JButton , etc) cursor using the setCursor() method.
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
One way we do this in our application is using IDisposable and then with using(){}
blocks to ensure the cursor is reset when done.
public class OverrideCursor : IDisposable
{
public OverrideCursor(Cursor changeToCursor)
{
Mouse.OverrideCursor = changeToCursor;
}
#region IDisposable Members
public void Dispose()
{
Mouse.OverrideCursor = null;
}
#endregion
}
and then in your code:
using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
// Do work...
}
The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.
Update
To prevent the cursor flickering you can do:
public class OverrideCursor : IDisposable
{
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With