In this tutorial, I will show you How to Move Controls With The Mouse On A Form At Runtime.
Giving the user the ability to ‘design’ their application is not difficult. All we have to do is make the respective controls movable.
For this we create a global list in which we cache the controls that we want to make movable.
1 2 3 |
List<Control> m_MovebleControls; |
Form_Load Event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private void Form1_Load(object sender, EventArgs e) { m_MovebleControls = new List<Control>(); m_MovebleControls.Add(comboBox1); m_MovebleControls.Add(button1); m_MovebleControls.Add(checkBox1); foreach (Control control in m_MovebleControls) { control.MouseMove += new MouseEventHandler(Control_MouseMove); } } |
Here we initialize the list of elements that can be moved and add the elements to this list using Add. Then we iterate over that list and subscribe to the MouseMove event for each element.
1 2 3 4 5 6 7 8 9 10 11 12 |
void Control_MouseMove(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Control controlToMove = (Control)sender; controlToMove.BringToFront(); controlToMove.Location = new Point(controlToMove.Location.X + e.Location.X - 10, controlToMove.Location.Y + e.Location.Y - 10); } } |
Here we only check whether the left mouse button was pressed and cast the event sender to a control. So that the control does not ‘disappear’ behind all the other controls, we still call .BringToFront () of the control and set the location of the control to the current mouse coordinates.
That’s all it was. Now you could add persistence in the form load and form close for the controls and nothing stands in the way of the user designing the forms.