在WinForm中,可以通過以下步驟實現控件自由拖動:
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;
這樣,當用戶在控件上按下鼠標左鍵并移動時,控件將根據鼠標移動的位置自由拖動。