11

我在控件上有一个 mousedown 事件和 click 事件。mousedown 事件用于启动拖放操作。我使用的控件是一个 Dirlistbox。

 Private Sub Dir1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Dir1.MouseDown

    Dim lab As New Label
    lab.Text = Dir1.DirList(Dir1.DirListIndex)
    lab.DoDragDrop(lab, DragDropEffects.Copy)

End Sub

但是当我单击控件时,只有 mousedown 事件会触发,click 事件不会触发。如果我在 mousedown 事件中注释掉“lab.DoDragDrop(lab, DragDropEffects.Copy)”,那么点击事件就会触发。当我单击控件时,我该怎么做才能触发 mousedown 和 click 事件?

4

2 回答 2

27

这是设计使然。MouseDown 事件捕获鼠标,Control.Capture 属性。内置的 MouseUp 事件处理程序检查鼠标是否仍然被捕获并且鼠标没有移动太远,然后触发 Click 事件。麻烦的是调用 DoDragDrop() 将取消鼠标捕获。必须如此,因为现在使用鼠标事件来实现拖放操作。所以你永远不会得到 Click 或 DoubleClick 事件。

需要响应点击拖放的控件是一个可用性问题。但是,它是可以修复的,您需要做的是确保用户已将鼠标从原来的鼠标向下位置移动了足够多,然后开始拖动。使您的代码如下所示:

Private MouseDownPos As Point

Private Sub Dir1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Dir1.MouseDown
    MouseDownPos = e.Location
End Sub

Private Sub Dir1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Dir1.MouseMove
    If e.Button And MouseButtons.Left = MouseButtons.Left Then
        Dim dx = e.X - MouseDownPos.X
        Dim dy = e.Y - MouseDownPos.Y
        If Math.Abs(dx) >= SystemInformation.DoubleClickSize.Width OrElse _
           Math.Abs(dy) >= SystemInformation.DoubleClickSize.Height Then
            '' Start the drag here
            ''...
        End If
    End If
End Sub
于 2013-02-06T15:39:45.533 回答
3

谁需要带有拖放功能的 c# 版本

    private Point MouseDownPos;
    private void dataGridView1_MouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e)
    {
        MouseDownPos = e.Location;
    }

    private void dataGridView1_MouseMove(System.Object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            dynamic dx = e.X - MouseDownPos.X;
            dynamic dy = e.Y - MouseDownPos.Y;
            if (Math.Abs(dx) >= SystemInformation.DoubleClickSize.Width || Math.Abs(dy) >= SystemInformation.DoubleClickSize.Height)
            {
                DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y);
                if (info.RowIndex >= 0)
                {
                    DataRowView view = (DataRowView)
                           dataGridView1.Rows[info.RowIndex].DataBoundItem;

                    if (view != null)
                        dataGridView1.DoDragDrop(view, DragDropEffects.Move);

                }
            }
        }
    }
于 2017-03-26T21:27:29.223 回答