在MouseDown期间检查面板是否已移动

时间:2013-01-03 15:11:59

标签: c# panels

我有一个面板,可以通过点击向左或向右移动(根据当前位置自动选择,距离是静态的)。此外,用户可以通过单击面板,按住按钮并移动鼠标来垂直拖动面板。问题是,当面板在垂直移动后被丢弃时,面板也会左/右移动,因此用户必须在之后再次单击它以获得正确的一侧(左/右)。以下是我使用的方法: 将事件处理程序添加到面板(此处称为Strip)

Strip.MouseDown += new MouseEventHandler(button_MouseDown);
Strip.MouseMove += new MouseEventHandler(button_MouseMove);
Strip.MouseUp += new MouseEventHandler(button_MouseUp);
Strip.Click += new EventHandler(strip_Click);

这里有上面提到的所有方法:

void button_MouseDown(object sender, MouseEventArgs e)
    {
        activeControl = sender as Control;
        previousLocation = e.Location;
        Cursor = Cursors.Hand;
    }

void button_MouseMove(object sender, MouseEventArgs e)
    {
        if (activeControl == null || activeControl != sender)
            return;

        var location = activeControl.Location;
        location.Offset(0, e.Location.Y - previousLocation.Y);
        activeControl.Location = location;
    }

void button_MouseUp(object sender, MouseEventArgs e)
    {
        activeControl = null;
        Cursor = Cursors.Default;
    }

void strip_Click(object sender, EventArgs e) // The one moving strip to left or right
    {
        activeControl = sender as Control;
            if (activeControl.Left != 30)
                activeControl.Left = 30;
            else
                activeControl.Left = 5;
    }

如何让面板在垂直移动时不向左或向右移动?

1 个答案:

答案 0 :(得分:2)

您需要区分点击和拖动。所以添加一个名为“dragged”的私有字段。

    private bool dragged;

在MouseDown事件处理程序中添加:

    dragged = false;

在MouseMove事件处理程序中添加:

    if (Math.Abs(location.Y - previousLocation.Y) > 
        SystemInformation.DoubleClickSize.Height) dragged = true;

在Click事件处理程序中添加:

    if (dragged) return;