Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Cursor.Show() and Cursor.Hide() not immediately hide or show the cursor?

Tags:

c#

winforms

I'm writing a drag system for a visualizer. When you click and drag, it moves what you see in the window. When the mouse hits the edge of the panel, I start repositioning the cursor so it never leaves the box. It keeps track of a virtual position where the cursor would be if it were inside the box. This portion of the code works fine.

Any time there is a MouseMoved event and the position is inside the box, I do Cursor.Show(). If it's outside the box, I do Cursor.Hide(). When the user lets go of the mouse button, I do Cursor.Show().

There are multiple issues. When the first Hide call happens, it doesn't hide. I have to get the cursor's virtual position outside the containing window for the hide to happen. When I move back in, it doesn't become visible, even though Show is being called. Finally, when releasing the mouse button, the cursor does not appear despite Show being called.

Rather than ask people to debug my code, I'm just wondering what's going on in the event system that makes Cursor.Hide/Show not work the way I'm expecting it to. My impression was that if a Control called Hide, the cursor would be hidden any time it was inside that control; likewise if I call show from a Control.

like image 759
Almo Avatar asked Oct 03 '11 19:10

Almo


2 Answers

For anyone having this problem, try something like that:

    private bool _CursorShown = true;
    public bool CursorShown
    {
        get
        {
            return _CursorShown;
        }
        set
        {
            if (value == _CursorShown)
            {
                return;
            }

            if (value)
            {
                System.Windows.Forms.Cursor.Show();
            }
            else
            {
                System.Windows.Forms.Cursor.Hide();
            }

            _CursorShown = value;
        }
    }

and use it:

CursorShown = false; // Will hide the cursor
CursorShown = false; // Will be ignored
CursorShown = true; // Will show the cursor
CursorShown = true; // Will be ignored
like image 80
Mr. Help Avatar answered Oct 04 '22 22:10

Mr. Help


Hans had it in the comment. Since this question has an answer, I feel it should have an answer.

"It is counted. Two shows and one hide does not hide the cursor." - Hans Passant

like image 23
Almo Avatar answered Oct 04 '22 21:10

Almo