Unsubscribing from the MouseMove event <i>from inside the handler...</i>
-
What's the explanation for why this doesn't work? What I'm after is a MouseMove handler that does not get called as a result of my programmatic mouse moves. (I know there aren't a lot of good reasons to move the cursor programmatically. This is just an example. I'm after the theory here). The result of this code is that the MouseMove handler is continuously called (as a result of the code that moves the mouse in the MouseMove handler). But why doesn't unsubscribing from the event prior to moving the mouse keep the handler from being called?
private void OnMouseMove(object sender, MouseEventArgs e)
{
// Unsubscribe from the MouseMove event because we don't want to respond to our programmatic mouse move.
this.MouseMove -= OnMouseMove;
// Move the mouse one pixel to the right just for kicks...
Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y);
// OK, hook it back up.
this.MouseMove += OnMouseMove;
}My best guess is that this is a threading issue. If that's the case, any ideas on how to fix it? Any ideas? Thanks! Ian
-
What's the explanation for why this doesn't work? What I'm after is a MouseMove handler that does not get called as a result of my programmatic mouse moves. (I know there aren't a lot of good reasons to move the cursor programmatically. This is just an example. I'm after the theory here). The result of this code is that the MouseMove handler is continuously called (as a result of the code that moves the mouse in the MouseMove handler). But why doesn't unsubscribing from the event prior to moving the mouse keep the handler from being called?
private void OnMouseMove(object sender, MouseEventArgs e)
{
// Unsubscribe from the MouseMove event because we don't want to respond to our programmatic mouse move.
this.MouseMove -= OnMouseMove;
// Move the mouse one pixel to the right just for kicks...
Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y);
// OK, hook it back up.
this.MouseMove += OnMouseMove;
}My best guess is that this is a threading issue. If that's the case, any ideas on how to fix it? Any ideas? Thanks! Ian
-
In that event handler, you unsubscribe the event, change the position of mouse pointer, and subscribe again. The event handler will be called again after that. For me, the codes works just fine.
But the handler is called in response to the move, which took place after I unsubscribed, and before I re-subscribed.