0

I have a control that has a Cursor property of type System.Windows.Forms.Cursor. Here's an example of what I'm trying to do:

if (someCondition)
{
    oldCursor = myControl.Cursor;
    myControl.Cursor = Cursors.Hand;
}
else
{
    myControl.Cursor = oldCursor;
}

I've stepped into the code using breakpoints and I can see that the logic is correct. However, when the control's Cursor property gets set back to oldCursor, the visual appearance of the cursor remains the same (e.g. Cursors.Hand).

I've noticed the CopyHandle() method within the Cursor class and am wondering if I need to use this in my copy operation somehow.

Can anybody give some insight into how to copy a Cursor reference?

Thick_propheT
  • 1,003
  • 2
  • 10
  • 29
  • There is no conceivable reason this won't work from the provided info, Winforms ensures that the cursor on the screen gets updated when the mouse is currently located on that control. You haven't explained enough, what else is going on? Check myControl.IsHandleCreated with the debugger. – Hans Passant Jan 28 '14 at 18:38

3 Answers3

0

The Cursor you are trying to capture is a Win32 resource in memory. You need its Handle as you suspect:

private IntPtr _prevCursor;

public MyClass()
{
    myControl.Cursor = Cursor.Default;
    _prevCursor = myControl.Cursor.Handle;
}

public SomeMethod()
{
    if (someCondition)
    {
        _prevCursor = myControl.Cursor.Handle;
        myControl.Cursor = Cursors.Hand;
    }
    else
    {
        myControl.Cursor = new Cursor(_prevCursor);
    }
}
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • I have implemented this, but it only works some of the time. I can't figure out why... I also tried using the CopyHandle() method instead of just using Handle and that kinda works. The cursor is the correct image, but it is scaled too small. Maybe the problem is that my initial cursor is a custom cursor? – Thick_propheT Jan 28 '14 at 21:37
  • Okay, I'm not sure what the problem was before when I was just saving a reference to the Cursor object itself, but I tried it again and it worked... maybe my reference to the control was incorrect... – Thick_propheT Jan 28 '14 at 22:43
0

Using a reference to the pure Cursor object DOES in fact work. I must have been doing something else wrong. I switched back to my original method (with a slight bit of refactoring) and everything works smoothly now.

Thanks anyway for the help, guys.

Thick_propheT
  • 1,003
  • 2
  • 10
  • 29
-1

You might need to call Application.DoEvents() after changing the cursor to get it to display the change

CDspace
  • 2,639
  • 18
  • 30
  • 36
  • `DoEvents()` is evil. And will not help, btw. See [this](http://stackoverflow.com/questions/11352301/how-to-use-doevents-without-being-evil) if you don't believe me. – DonBoitnott Jan 28 '14 at 18:45