【问题标题】:Listbox mousedown event returns previously selected item列表框 mousedown 事件返回先前选择的项目
【发布时间】:2019-08-20 12:18:03
【问题描述】:

我正在为许多列表框准备拖放解决方案。问题是,当我单击列表中的某个项目时,Windows(或任何人)将该项目设置为蓝色,触发mousedown 事件,但mousedown 事件处理程序中处理的.Selected().Listindex 方法都返回之前选择的项目。通过再次单击(已经是蓝色的)项目,他们会正确返回项目。

会发生什么情况是我按住鼠标按钮单击一个项目,该项目变为蓝色,我将它拖到另一个列表框,之前选择的项目到达那里。

Private Sub pThisListBox_Mousedown(ByVal Button As Integer, _
           ByVal Shift As Integer, _
           ByVal X As Single, _
           ByVal Y As Single)

    Dim MyDataObject As DataObject
    Dim sSelected As String
    Dim i As Long
    Dim Effect As Integer

    If Button = 1 Then
        sSelected = vbNullString

变量 #1

        For i = 0 To pThisListBox.ListCount - 1
            If pThisListBox.Selected(i) Then
                sSelected = pThisListBox.List(i)
                Exit For
            End If
        Next

变量 #2

        With pThisListBox
            If .ListIndex >= 0 Then
                sSelected = .List(.ListIndex)
            End If
        End With

常见

        If LenB(sSelected) = 0 Then Exit Sub
        Set DragSource = pThisListBox
        Set MyDataObject = New DataObject
        MyDataObject.SetText sSelected
        Effect = MyDataObject.StartDrag
        Debug.Print sSelected
    End If

End Sub

我已经尝试过使用.MultiSelect,但没有帮助。它实际上设置为fmMultiSelectSingle,但理想的设置为fmMultiSelectMulti。 我是不是误会了什么?

【问题讨论】:

  • 您是否尝试过使用 MouseMove 而不是 MouseDown?

标签: vba drag-and-drop listbox


【解决方案1】:

试试这个(也适用于多选)

Private Sub pThisListBox_MouseMove(ByVal Button As _
 Integer, ByVal Shift As Integer, ByVal X As _
 Single, ByVal Y As Single)
 Dim MyDataObject As DataObject

 If Button = 1 Then
 Set MyDataObject = New DataObject
 Dim Effect As Integer
    For i = 0 To pThisListBox.ListCount - 1
            If pThisListBox.Selected(i) Then
                MyDataObject.Clear
                MyDataObject.SetText pThisListBox.List(i)
                Effect = MyDataObject.StartDrag
               End If
        Next
 End If
End Sub

【讨论】:

  • 谢谢,MouseMove 是处理此问题的正确事件。它工作完美。 MouseDown 在更新 .Selected.Listindex 之前触发。
  • mouse_up 可以工作并且超级容易编码,看看我的答案。
【解决方案2】:

简单的解决方案是正确的。

如果mouse_down事件太早,就去mouse_up事件。

我试过了,效果很好。这是一个代码示例:

Private Sub Listbox_Mouseup(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

Dim Bonus$, i&

i = Listbox.ListIndex
Bonus = Listbox.List(i, 0)

If Button = 1 Then      
      Me.Caption = Bonus
End If

End Sub

为了不让它看起来很奇怪,在 mouse_down 上,我会 me.caption=""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多