如何实现控件在容器中来回拖动?
自己用C#做了一个棋子游戏但想不出方法让棋子在容器中实现来回拖动,想请问一下各位高手应该怎么做到控件的来回拖动,还要提取目标位置的具体坐标。首先申明棋子都是动态添加到窗体的Label控件。谢谢各位
程序代码: public delegate void ClickLine(object sender, MouseEventArgs e);
public event ClickLine OnClickLine;
private void UserLine_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (OnClickLine != null)
{
OnClickLine(sender, e);
}
}
} //如果你的棋子是WINDOWS里自带的控件来做的话,上面的东西就不用,直接用它的MouseClick事件就可以,如果不是,要写在自定义的控件里面
void Box_OnClickLine(object sender, MouseEventArgs e)
{
_isMove = true;//确定开始移动操作
_clickControl = (UserLine)sender;
}
在棋子里再设定一个鼠标放开的事件,然后:
程序代码: void Box_MouseUp(object sender, MouseEventArgs e)
{
_isMove = false;//结束移动操作
_clickControl.Location = new Point(e.X, e.Y);//这里自己微调坐标
}
如果要实现棋子随鼠标动的话,在这个棋子的容器控件里:
程序代码: bool _isMove = false;
Control _clickControl = null;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_isMove)
{
_clickControl.Location = new Point(e.X, e.Y);
}
}
大概就是这样了,有不清楚的再说吧
程序代码: public partial class Man : UserControl
{
public Man()
{
InitializeComponent();
}
bool _isMove = false;//移动状态
Point _clickPoint;//鼠标点击时的位置
private void Man_MouseUp(object sender, MouseEventArgs e)
{
_isMove = false;
}
private void Man_Paint(object sender, PaintEventArgs e)
{
this.BringToFront();//把控件置于顶层
}
private void Man_MouseDown(object sender, MouseEventArgs e)
{
//只影响鼠标左键单击
if (e.Button != System.Windows.Forms.MouseButtons.Left)
return;
_isMove = true;
_clickPoint = e.Location;
//这里还可以改变控件的显示,例如虚化
}
private void Man_MouseMove(object sender, MouseEventArgs e)
{
if (_isMove)
{
//鼠标的屏幕坐标计算成当前控件在父窗口的Location
Point newPoint = this.Parent.PointToClient(Cursor.Position);
//修正坐标,保持控件与鼠标点击时位置相同
this.Location = new Point(newPoint.X - _clickPoint.X, newPoint.Y - _clickPoint.Y);
}
}
}昨天那个是想象的,今天试了一下,换了一个事件,做了些小调整