简体   繁体   中英

Why isn't the control moving?

About 5 years ago I created an app that allowed me to drag controls around inside a Panel control.

I know how to move things around.

The problem is that I have lost my backup code, and cannot remember/figure out how I did it before.

Controls are created dynamically, when I click a button (like, Add Button, for example).

so:

bool mouseDown;
Point lastMouseLocation = new Point();
Control SelectedControl = null;

void AddButton_Click(object sender, EventArgs e)
{
   // Create the control.
   Button button = new Button();
   button.Location = new Point(0,0);
   button.Text = "hi lol";

   // the magic...
   button.MouseDown += button_MouseDown;
   button.MouseMove += button_MouseMove;
   button.MouseUp += button_MouseUp;

   button.Click += button_Click;
}

void button_Click(object sender, EventArgs e)
{
   SelectedControl = sender as Control; // This "selects" the control.
}

void button_MouseDown(object sender, EventArgs e)
{
   mouseDown = true;
}

void button_MouseMove(object sender, EventArgs e)
{
   if(mouseDown)
   {
      SelectedControl.Location = new Point(
         (SelectedControl.Location.X + e.X) - lastMouseLocation.X,
         (SelectedControl.Location.Y + e.Y) - lastMouseLocation.Y
      );
   }
}

void button_MouseUp(object sender, EventArgs e)
{
   mouseDown = false;
}

So basically what I am trying to do is when a user clicks any control on the form, it then "selects it", then they can move it around.

But the problem is, I don't remember how to do it right, so that I can have just 1 set of handlers for MouseDown,Up,Move etc and SelectedControl that can represent all controls added to the Panel.

How can I do this?

Here is the code I used frequently which is more concise:

Point downPoint;
void button_MouseDown(object sender, MouseEventArgs e)
{
  downPoint = e.Location;
}

void button_MouseMove(object sender, MouseEventArgs e)
{    
  if(MouseButtons == MouseButtons.Left){
      Button button = sender as Button;
      button.Left += e.X - downPoint.X;
      button.Top += e.Y - downPoint.Y;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM