检查面板是否在按下鼠标时移动

本文关键字:鼠标 移动 是否 检查 | 更新日期: 2023-09-27 17:50:45

我有一个面板,可以向左或向右移动(根据其当前位置自动选择,距离是静态的)通过点击。此外,用户可以通过单击面板,按住按钮并移动鼠标来垂直拖动面板。问题是,当面板在垂直移动后被放下时,它也会向左/向右移动,所以用户必须在之后再次点击它,才能到达正确的一侧(左/右)。以下是我正在使用的方法:向面板添加事件处理程序(这里称为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;
    }

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

检查面板是否在按下鼠标时移动

您需要区分单击和拖动。所以添加一个名为"drag "的私有字段。

    private bool dragged;

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

    dragged = false;

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

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

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

    if (dragged) return;