如何启用和禁用拖动按钮?

时间:2019-07-26 07:20:06

标签: winforms drag-and-drop

我有一个表格。在此表单上有一个按钮和一个面板。两者都有相同的父对象:表单。我希望能够启用或禁用按钮的拖动操作。我正在使用的代码是:

ObjectMapper mapper = new ObjectMapper();
Class<?> view = Pojo.Response2.class;  // runtime assignment of view
mapper.writerWithView(view).writeValue(System.out, pojo);

即使我有以下声明:this.AllowDrop = false; ,panel1.AllowDrop = false;和button1.Draggable(false);以及应该禁止拖动的重写void WndProc方法, button1始终是可拖动的。

1 个答案:

答案 0 :(得分:0)

我因此更改了事件处理程序:

private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        if (sender is Button)
        {
            Button senderButton = (Button)sender;
            if (enableDragOperations)
            {
                if (e.Button == MouseButtons.Left)
                {
                    isDragged = true;
                    Point ptStartPosition = senderButton.PointToScreen(new Point(e.X, e.Y));

                    pointOffset = new Point();
                    pointOffset.X = senderButton.Location.X - ptStartPosition.X;
                    pointOffset.Y = senderButton.Location.Y - ptStartPosition.Y;
                }
                else
                {
                    isDragged = false;
                }
            }
        }
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (sender is Button)
        {
            Button senderButton = (Button)sender;
            if (enableDragOperations)
            {
                if (isDragged)
                {
                    Point newPoint = senderButton.PointToScreen(new Point(e.X, e.Y));
                    newPoint.Offset(pointOffset);
                    senderButton.Location = newPoint;
                }
            }
        }
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        if (sender is Button)
        {
            Button senderButton = (Button)sender;
            if (enableDragOperations)
            {
                Point newPoint = senderButton.PointToScreen(new Point(e.X, e.Y));
                isDragged = false;
            }
        }
    }

我定义了一个全局字段:bool enableDragOperations并将其设置为false。