I'm having some trouble with figuring out a way of unsubscribing from some anonymous delegate events that i found in a pre-made helper file that helps allow movement of controls at run time. The reason i want to unsubscribe to these events is so that the control (in this case buttons) will become locked again and not able to be moved. Here is the method in the helper class:
public static void Init(Control control)
{
Init(control, Direction.Any);
}
public static void Init(Control control, Direction direction)
{
Init(control, control, direction);
}
public static void Init(Control control, Control container, Direction direction)
{
bool Dragging = false;
Point DragStart = Point.Empty;
control.MouseDown += delegate(object sender, MouseEventArgs e)
{
Dragging = true;
DragStart = new Point(e.X, e.Y);
control.Capture = true;
};
control.MouseUp += delegate(object sender, MouseEventArgs e)
{
Dragging = false;
control.Capture = false;
};
control.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (Dragging)
{
if (direction != Direction.Vertical)
container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
if (direction != Direction.Horizontal)
container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
}
};
}
and here's how i subscribe to these events by calling the method;
ControlMover.Init(this.Controls["btn" + i]);
I've read about some methods on MSDN about unsubscribing to these by creating a local variable holding these events and then unsubscribing through this way, but i can't seem to get this working in my own project. How do i go about unsubscribing to these events so that my controls become fixed in position again?
Anonymous delegates are not guaranteed to be unique as created by the compiler, when unsubscribing this lack of uniqueness of the same code will cause it to fail to unsubscribe the correct handler. The only way to do so safely is to keep a reference to the delegate and use that to unsubscribe, or change it to a full method.
Delegates are equal based on object instance and method signature I believe.
A possible duplicate:
How to remove a lambda event handler
Basically, keep a reference:
MouseEventHandler handler = (sender, e) =>
{
Dragging = true;
DragStart = new Point(e.X, e.Y);
control.Capture = true;
};
control.MouseDown += handler;
control.MouseDown -= handler;
Or turn the anonymous method into a proper method.
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