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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With