仅在按下左键单击时捕获鼠标移动事件

时间:2011-10-28 22:06:23

标签: c# .net winforms events

只有当鼠标按下鼠标左键移动时,我才需要更新控件。我通常会检查e.Button属性,但它在MouseEnter事件中不可用。

void MyControl_MouseEnter(object sender, EventArgs e)
    {
        // MouseEventArgs needed to check this

        // if (e.Button == MouseButtons.Left)
        // {
        //     update MyControl
        // }
    }

你将如何实现这一目标?

5 个答案:

答案 0 :(得分:5)

使用静态Control.MouseButtons属性。例如:

    private void panel1_MouseEnter(object sender, EventArgs e) {
        if (Control.MouseButtons == MouseButtons.Left) {
            // etc...
        }
    }

非常很难开始,无论用户点击什么来按下鼠标按钮都会捕获鼠标,从而阻止控件的MouseEnter事件被触发。它也是用户完全无法发现的UI。请考虑更好的鼠标陷阱。

答案 1 :(得分:2)

这是一种(原始)方式。当您将鼠标拖动到button1时,它会将表单的标题文本更改为按下的鼠标按钮。您可以参考Control.MouseButtons以查看哪个按钮处于按下状态。以下是MSDN的更多信息。

 public partial class Form1 : Form
    {
        MouseButtons _buttons;

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_buttons != System.Windows.Forms.MouseButtons.None)
            {
                this.Text = _buttons.ToString();
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            _buttons = Control.MouseButtons;
        }
    }

答案 2 :(得分:1)

我在SO上找到了另一个问题的答案:

How can I detect a held down mouse button over a PictureBox?

您需要使用消息过滤器。实现IMessageFilter接口的PreFilterMessage,并使用Application.AddMessageFilter分配实例。

你必须自己解释Windows消息......这并不困难,但需要一些工作。

实施可能如下所示:

        if (m.Msg == 0x200)
        {
            int x, y;
            x = m.LParam.ToInt32() & 0xFFFF;
            y = m.LParam.ToInt32() >> 16;
            if ((m.WParam.ToInt32() & 2) != 0)
            {
                // here, the left mouse button is pressed, and you can use the coords
                // and see if the mouse is over the control you want.
            }
        }

答案 3 :(得分:1)

我今天刚刚实现了类似的功能,仅在Chrome中进行了测试,但效果相当不错。基本概念是您只在mousedown和mouseup之间捕获mousemove,如下所示:

var image = document.getElementById('my_image');
image.addEventListener('mousedown', function(e) {
    e.currentTarget.addEventListener('mousemove', doMyStuff);
});
image.addEventListener('mouseup', function(e) {
    e.currentTarget.removeEventListener('mousemove', doMyStuff);
});

function doMyStuff(e) {
    // do what you want, the mouse is moving while the user is holding the button down
}

答案 4 :(得分:-1)

   Private Sub Button1_MouseDown(sender As Object, e As MouseEventArgs) Handles 
        Button1.MouseDown
        If Control.MouseButtons = MouseButtons.Left Then
            Label1.Text = "Left"
        ElseIf Control.MouseButtons = MouseButtons.Right Then
            Label1.Text = "Right"
        ElseIf Control.MouseButtons = MouseButtons.Middle Then
            Label1.Text = "Middle"
        Else
            Label1.Text = "lelse"
        End If
    End Sub