如何在绘制后移动形状

时间:2014-04-05 06:52:20

标签: c#

移动我绘制的形状时遇到问题,当我点击该行并拖动它时,它变为2行,我认为问题出在我的鼠标事件代码中,这是我的鼠标事件代码:

private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            if (obj.IsPointOnLine(e.Location, 5) == true)
            {
                this.Cursor = Cursors.SizeAll;
                obj.isDragging = true;
                deltaStart = new Point(obj.mstartpoint.X - e.Location.X, obj.mstartpoint.Y - e.Location.Y);
                deltaEnd = new Point(obj.mendpoint.X - e.Location.X, obj.mendpoint.Y - e.Location.Y);
            }
            else if (obj.IsPointOnLine(e.Location, 5) == false)
            {
                this.Cursor = Cursors.Cross;
                obj.mstartpoint = e.Location;
            }
        }
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (obj.isDragging && deltaStart != null && deltaEnd != null)
        {
            obj.mstartpoint = new Point(deltaStart.X + e.Location.X, deltaStart.Y + e.Location.Y);
            obj.mendpoint = new Point(deltaEnd.X + e.Location.X, deltaEnd.Y + e.Location.Y);
            Refresh();
            Update();
        }
        else if ((Control.ModifierKeys & Keys.Shift) != 0)
        {
            if ((Control.MouseButtons & MouseButtons.Left) != 0)
            {
                obj.mendpoint = e.Location;
                switch (obj.mshape)
                {
                    case 1:
                        obj.mshape = 3;
                        break;
                    case 2:
                        obj.mshape = 4;
                        break;
                }
                Invalidate();
            }
        }
        else if (e.Button == MouseButtons.Left)
        {
            obj.mendpoint = e.Location;
            switch (obj.mshape)
            {
                case 3:
                    obj.mshape = 1;
                    break;
                case 4:
                    obj.mshape = 2;
                    break;
            }
            Invalidate();
        }          
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        obj.isDragging = false;
        this.Cursor = Cursors.Default;
        MyObject a = new MyObject(obj.mstartpoint, obj.mendpoint, obj.mshape, obj.mwidth, obj.mcolor);
        ds.Add(a);
    }

如果你没有下载我的源代码:https://www.dropbox.com/s/rdk88k4661zc3nj/WindowsFormsApplication19.rar 请解决我的问题,谢谢你,抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

如果想要实现画布来拖动元素,可以选择DragCanvas。

Dragging Elements in a Canvas from Josh Smith以及适应Josh Smith代码的Dragging Elements in a Canvas from igkutikov之后。有#mustread类别的文章。

使用dragCanvas,您可以实现拖动元素画布的全部功能,并更好地适应您的代码。快乐的编码!