65.9K
CodeProject is changing. Read more.
Home

Simple Application Cursor Management

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jan 13, 2012

CPOL
viewsIcon

17853

Cursors

This simple class will assist you in managing cursors within an application. The class is self explanatory, however ensure you call the cursor reset each time in order to remain in sync.
    public static class ManageCursor
    {

        public static System.Collections.Generic.Stack<System.Windows.Forms.Cursor> cursorStack = new Stack<System.Windows.Forms.Cursor>();
        public static System.Collections.Generic.Stack<IntPtr> controlStack = new Stack<IntPtr>();

        #region Cursor Management...

        public static void SetCursor(System.Windows.Forms.Form frm, System.Windows.Forms.Cursor cursor)
        {            
            cursorStack.Push(cursor);
            controlStack.Push(frm.Handle);
            frm.Cursor = cursor;
        }
        public static void SetCursor(System.Windows.Forms.Control ctrl, System.Windows.Forms.Cursor cursor)
        {
            cursorStack.Push(cursor);
            controlStack.Push(ctrl.Handle);
            ctrl.Cursor = cursor;
        }

        public static void ResetCursor(System.Windows.Forms.Form frm)
        {
            if (cursorStack.Count == 0)
                frm.Cursor = System.Windows.Forms.Cursors.Default;
            else
            {
                cursorStack.Pop();
                controlStack.Pop();
                if (cursorStack.Count == 0)
                    frm.Cursor = System.Windows.Forms.Cursors.Default;
                else if (controlStack.Peek() == frm.Handle)
                    frm.Cursor = cursorStack.Peek();
                else
                    frm.Cursor = System.Windows.Forms.Cursors.Default;
            }
        }
        public static void ResetCursor(System.Windows.Forms.Control ctrl)
        {
            if (cursorStack.Count == 0)
                ctrl.Cursor = System.Windows.Forms.Cursors.Default;
            else
            {
                cursorStack.Pop();
                controlStack.Pop();
                if (cursorStack.Count == 0)
                    ctrl.Cursor = System.Windows.Forms.Cursors.Default;
                else if (controlStack.Peek() == ctrl.Handle)
                    ctrl.Cursor = cursorStack.Peek();
                else
                    ctrl.Cursor = System.Windows.Forms.Cursors.Default;
            }
        }

        public static void ClearCursors()
        {
            cursorStack.Clear();
        }

        #endregion

    }
To implement is as simple as...
ManageCursor.SetCursor(this, System.Windows.Forms.Cursors.WaitCursor);
                
//Do your stuf...
                 
ManageCursor.ResetCursor(this);
A small contribution, but a contribution never the less!
Simple Application Cursor Management - CodeProject