Window我们可以用DragMove()函数实现,如果是控件呢?怎么实现拖动?

解决方案 »

  1.   

    用鼠标的坐标赋值给控件的location来实现
      

  2.   

    MouseDown中置标记isdown=true,MouseMove中,如果isdown,则根据鼠标位置控制控件的left和top,MouseUp事件中,isdown=false
      

  3.   

    拖动一个按钮定义private System.Windows.Forms.Button button1;
    private bool Mousedown = false;  //鼠标按下为true
    private int CurX = 0,CurY = 0;
    事件private void button1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
    if(Mousedown)
    {
    //Cursor.Position .X Cursor.Position .Y 是屏幕坐标
    //用屏幕坐标减窗口坐标以保持鼠标总是在窗口的原位置.
    Point sp = new Point(Cursor.Position.X,Cursor.Position.Y);
    Point np = this.PointToClient(sp);
    this.button1.Location = new Point(np.X - CurX,np.Y - CurY);//(Cursor.Position .X - CurX,Cursor.Position .Y - CurY);
    }
    } private void button1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
    CurX = e.X;//保存鼠标按下是鼠标在窗口的坐标
    CurY = e.Y;
    Mousedown = true;
    this.button1.Capture = true;
    } private void button1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
    {
    Mousedown = false;
    this.button1.Capture = false;
    }
      

  4.   

          [DllImport("user32.dll")]
            static extern bool ReleaseCapture();
            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, UInt32 lParam);        private readonly UInt32 WM_SYSCOMMAND = 0x112;
            private readonly UInt32 SC_MOVE = 0xF010;
            private readonly UInt32 HTCAPTION = 2;
            
            private void button1_Click(object sender, EventArgs e)
            {
                MessageBox.Show("1");
            }        private void button1_MouseMove(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Left)
                {
                    ReleaseCapture();
                    SendMessage(button1.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
                }
            }
      

  5.   

    http://download.csdn.net/detail/wangyue4/2874530
    c# 实现任意控件的拖拽
    我自己写的