当我想在Form中进行控件的拖动, 我将button作为一个控件来控制. 当我点击的时候

1: 当我点击的时候,可以随便于工作的出来几个button.

2: 可以将点击出来后的控件进行拖动,而且每个控件都可以进行拖动

Button c = new Button();
        private Point downPoint;
        private Rectangle downRectangle;
        private Rectangle lastRectangle;
        int buttonindex = 0;

        public void butto()
        {
            Button button = new Button();
            button.Parent = this;
            button.Text = "按钮" + buttonindex;
            buttonindex++;
            this.Controls.Add(button);
            button.MouseDown += new MouseEventHandler(button_MouseDown);
            button.MouseMove += new MouseEventHandler(button_MouseMove);
            button.MouseUp += new MouseEventHandler(button_MouseUp);
            c = button ;
            button = c ;
        }

        private void button_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            c  = sender as Button ;//表示都可以移动的.如果不用这句话的话.
                                   //表示最后一个控件的进行移动.
            downPoint = e.Location;

            lastRectangle =
             new Rectangle(0, 0, c.Width, c.Height);
            downRectangle.Offset(((Control)sender).PointToScreen(new Point(0, 0)));
            ControlPaint.DrawReversibleFrame(
                downRectangle, Color.White, FrameStyle.Thick);
            lastRectangle = downRectangle;
        }

        private void button_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            ControlPaint.DrawReversibleFrame(
                downRectangle, Color.White, FrameStyle.Thick);

            Rectangle rectangle = downRectangle;
            rectangle.Offset(e.X - downPoint.X, e.Y - downPoint.Y);
            ControlPaint.DrawReversibleFrame(
                rectangle, Color.White, FrameStyle.Thick);
            lastRectangle = rectangle;
        }

        private void button_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            ControlPaint.DrawReversibleFrame(
                lastRectangle, Color.White, FrameStyle.Thick);
            c.Location = new Point(
                 ((Control)sender).Location.X + e.X - downPoint.X,
                  ((Control)sender).Location.Y + e.Y - downPoint.Y);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            butto();
        }

Posted on 2008-08-22 15:00  Yongming Ye  阅读(204)  评论(0编辑  收藏  举报