Reputation: 13
So I have this condition which snaps a GUI object to a guide line object. What I want is for the object to snap in place but if the system still detects mouse movement then I want that object to unsnap and continue moving. I have the snapping condition working but I am failing on the latter.
This is the event that I am firing and it is constantly being listened to by the system
private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseCaptured && snappedVertically) //The IsMouseCaptured listens for mouse movement and snapped vertically is what I am using to snap the GUI element
{
if (snappedVertically)
{
Thread.Sleep(2000); //wait 2 seconds...
snappedVertically = false; //...then unsnap
}
}
}
The problem is that there's latency in the application which then becomes unresponsive and I have to do a force restart. Can someone help me out with this issue?
Upvotes: 1
Views: 1288
Reputation: 6220
Sleeping the UI thread is what is causing the unresponsiveness.
Your problem can be solved by just comparing the timing of events:
DateTime _lastEventTime = DateTime.MinValue;
private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseCaptured && snappedVertically) //The IsMouseCaptured listens for mouse movement and snapped vertically is what I am using to snap the GUI element
{
if (snappedVertically)
{
if ((DateTime.Now - _lastEventTime) < TimeSpan.FromSeconds(2))
{
snappedVertically = false;
}
}
}
_lastEventTime = DateTime.Now;
}
Your question isn't terribly clear on the desired behaviour, but here, we record the last event time after each firing, and then if we're snapped vertically, check if the last event happened less than 2 seconds ago, if it did, then we want to unsnap.
As per comment clarifying the intention of the question, you can toggle a value after 2 seconds easily as such:
private async void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseCaptured && snappedVertically) //The IsMouseCaptured listens for mouse movement and snapped vertically is what I am using to snap the GUI element
{
if (snappedVertically)
{
await Task.Delay(2000);
snappedVertically = false;
}
}
}
Just be careful, because obviously when waiting for those 2 seconds, the user could move the mouse again, which will once again set a new timer waiting 2 seconds and so on and so on; you'll most likely want to prevent multiple delays, but that's an exercise for you.
Upvotes: 1
Reputation: 31
Maybe you could use another Method, e.g. UIElement.IsMouseOver
, to satisfy that the mouse cursor is hovering over a certain object? Then you wouldn't need to sleep any thread.
As stated before, your question is not very clear about the bigger picture.
Upvotes: 0