Home > database >  Changing mouse pointer not maintained in c# WinForms
Changing mouse pointer not maintained in c# WinForms

Time:10-27

I have a WinForms application that simply has one button. I created this application to demonstrate what is happening on a much larger application.

The button changes a boolean from true to false, and sets the mouse pointer.

private bool ChangeMouse = true;

private void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("CURSOR-TOP: "   System.Windows.Forms.Cursor.Current.ToString());

    if (ChangeMouse)
    {
        ChangeMouse = false;
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Cross;
    }
    else
    {
        ChangeMouse = true;
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
    }

    Console.WriteLine("CURSOR-BOTTOM: "   System.Windows.Forms.Cursor.Current.ToString());
    Console.WriteLine("");
}

This is the result I get when i click the button 4 times:

CURSOR-TOP: [Cursor: Default]
CURSOR-BOTTOM: [Cursor: Cross]

CURSOR-TOP: [Cursor: Default]
CURSOR-BOTTOM: [Cursor: Default]

CURSOR-TOP: [Cursor: Default]
CURSOR-BOTTOM: [Cursor: Cross]

CURSOR-TOP: [Cursor: Default]
CURSOR-BOTTOM: [Cursor: Default]

As can be seen, the value for CURSOR-TOP is always the Default Cursor. Why is the change to the current cursor not maintained???

CodePudding user response:

this.Cursor must be used instead of System.Windows.Forms.Cursor.Current.

As to why? I really don't know.

CodePudding user response:

This doesn't really answer your question, but...

I use this code all the time (I have it in maybe 10 desktop utility apps):

using System;
using System.Windows.Forms;

namespace MyAppsNamespace
{
    public class WorkingCursor : IDisposable
    {
        private readonly Cursor _oldCursor;

        public WorkingCursor()
        {
            _oldCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
        }

        public void Dispose()
        {
            Cursor.Current = _oldCursor;
        }
    }
}

You consume it this way:

using (new WorkingCursor()) {
    DoSomethingThatTakesAWhile();
}

It always just works like a charm. Not sure why you are having this issue

  • Related