在WinForm中,可以通過(guò)以下步驟實(shí)現(xiàn)控件自由拖動(dòng):
private Point mouseOffset;
private void Control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control control = (Control)sender;
mouseOffset = new Point(e.X, e.Y);
}
}
private void Control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control control = (Control)sender;
control.Left = e.X + control.Left - mouseOffset.X;
control.Top = e.Y + control.Top - mouseOffset.Y;
}
}
private void Control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control control = (Control)sender;
control.Capture = false;
}
}
// 綁定事件
yourControl.MouseDown += Control_MouseDown;
yourControl.MouseMove += Control_MouseMove;
yourControl.MouseUp += Control_MouseUp;
這樣,當(dāng)用戶在控件上按下鼠標(biāo)左鍵并移動(dòng)時(shí),控件將根據(jù)鼠標(biāo)移動(dòng)的位置自由拖動(dòng)。