Changing the cursor in WPF sometimes works, sometimes doesn't

后端 未结 5 618
[愿得一人]
[愿得一人] 2020-11-28 23:08

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

5条回答
  •  [愿得一人]
    2020-11-28 23:40

    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 s_Stack = new Stack();
    
      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;
      }
    
    }
    

提交回复
热议问题