You don't share the code in MethodX, but it seems clear you want to move your Custom Control (a UserControl ?) around, and keep it within the boundaries of the Control/Form it is contained within.
There is nothing
wrong with using += and -= in your code to install, and uninstall, EventHandlers !
What is questionable about what you are doing now is:
1. you are instantiating new
EventHandlers in every MouseDown and MouseLeave Event; there's no need to do that (see code below). Every time you use "new MouseEventHandler(...)" you are allocating a new
EventHandler object ! An interesting thing about using -= to remove an EventHandler is that it will not throw an error if the EventHandler you try to remove does not exist in the Multicast delegate that is stored in the Object's for the Event. So your code just "piles on" multiple EventHandlers !
2. you are not implementing ... that we can see ... code that actually moves the Custom Control only
when the mouse is down.
The other issue here is how to keep the Custom Control inside the boundaries of its container: to do that you need to set the clipping Rectangle for the Custom Control in the MouseDown Event, and "undo" that clipping Rectangle in the MouseUp Event. We'll get to that.
private bool IsMouseDown = false;
private int mouseDownX;
private int mouseDownY;
private void CustomControl_MouseDown(object sender, MouseEventArgs e)
IsMouseDown = true;
mouseDownX = e.X;
mouseDownY = e.Y;
private void CustomControl_MouseUp(object sender, MouseEventArgs e)
IsMouseDown = false;
private void CustomControl_MouseMove(object sender, MouseEventArgs e)
CustomControl.Left += e.X - mouseDownX;
CustomControl.Top += e.Y - mouseDownY;
This is all very standard code, and I would guess you are already familiar with it. If you wish to "turn on" and "turn off" the CustomControl being movable
in your code you are going to need to implement something like this:
private void SetCustomControlMovable(bool isMovable)
CustomControl.MouseDown += CustomControl_MouseDown;
CustomControl.MouseUp += CustomControl_MouseUp;
CustomControl.MouseMove += CustomControl_MouseMove;
CustomControl.MouseDown -= CustomControl_MouseDown;
CustomControl.MouseUp -= CustomControl_MouseUp;
CustomControl.MouseMove -= CustomControl_MouseMove;
So, in this case, you would not
assign the EventHandlers to your CustomControl at design-time.
Now, we can address the issue of how to keep your Control constrained to move inside the boundaries of its container Control (or Form, or whatever). In this post: [^
], I show how to do that.