Nov
4
2009
WPF // MVVM

WPF Cursor Handling Routine

In my WPF application I need to change the cursor to identify a potentially long running process. The cursor needs to change back when the process completes regardless if it throws back an exception or not. So I ended up writing the class below to do just that.

public class CursorRoutine : IDisposable
    {
        private System.Windows.Input.Cursor _oldCursor;
        public CursorRoutine()
            : this(null)
        {
        }
        public CursorRoutine(System.Windows.Input.Cursor oldCursor)
            : this(oldCursor, System.Windows.Input.Cursors.Wait)
        {
        }
        public CursorRoutine( System.Windows.Input.Cursor oldCursor, System.Windows.Input.Cursor newCursor)
        {
            _oldCursor = oldCursor;
            System.Windows.Input.Mouse.OverrideCursor = newCursor;
        }

        #region IDisposable Members

        private bool isDisposed;
        /// 
        /// Finilize method
        /// 
        ~CursorRoutine()
        {
            Dispose(false);
        }
        /// 
        /// Releases all resources used by the object
        /// 
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// 
        /// Releases all resources used by the object
        /// 
        /// Disposing Flag
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    //Dispose of managed resources
                    System.Windows.Input.Mouse.OverrideCursor = _oldCursor;
                }
                //Dispose of unmanaged resources
            }
            isDisposed = true;
        }

        #endregion 
    }

The it can be used like that:

using (CursorRoutine cursor = new CursorRoutine())
{
    //...... A call to a long running process
}