1
votes

I have a ListBox in my program with SelectionMode set to MultiExtended. The items within the ListBox are added by the user through a TextBox. Currently, the only purpose of selecting an item in the ListBox is to remove those items, which is currently done by right clicking on a selected item.

I want to also allow the user to remove selected items by pressing the Delete key, so long as the ListBox is the focused control. When the focused control becomes any other control I'd like the selected items to clear, which I do by:

Private Sub LstbxTaskIDs_Leave(sender As Object, e As EventArgs) Handles lstbxTaskIDs.Leave
    lstbxTaskIDs.ClearSelected()
End Sub

This part works fine, but then if the user clicks back onto the ListBox, but not onto an item (i.e. an empty region of the control) then either the first item, or the previously selected item (depending on if only one item or multiple items were previously selected) are selected automatically. Or, to put this more succintly:

  1. User selects item(s) in ListBox.
  2. User clicks elsewhere on the form.
  3. Selected item(s) are deselected.
  4. User clicks on empty region of ListBox.
  5. The first item (or the last selected item) are automatically selected.

The only change I'd like is for no items to become automatically selected upon re-entering the ListBox. (Note: an item will only be automatically selected if an item was previously selected. If you click on an empty region before ever selecting an item, no item becomes automatically selected.)

This is what I tried, but it doesn't seem to change anything:

Private Sub LstbxTaskIDs_Enter(sender As Object, e As EventArgs) Handles lstbxTaskIDs.Enter
    lstbxTaskIDs.ClearSelected()
End Sub

I have also tried replacing lstbxTaskIDs.ClearSelected() with lstbxTaskIDs.SelectedItems.Clear() and lstbxTaskIDs.SelectedItem = -1

1
BeginInvoke(new Action(Sub() lstbxTaskIDs.ClearSelected())) – Jimi
@Jimi Placed this in the Enter handler and it made it work exactly as I was hoping for, thank you! – Tyler N

1 Answers

1
votes
BeginInvoke(new Action(Sub() lstbxTaskIDs.ClearSelected()))

Will still select and then unselect an item in the ListBox, which raises the SelectedIndexChanged event.

To avoid that, try intercepting the MouseDown and see if it is clicking on an empty space.

Public Class ListBoxEx
  Inherits ListBox

  Private Const WM_LBUTTONDOWN As Integer = &H201

  Protected Overrides Sub WndProc(ByRef m As Message)
    If m.Msg = WM_LBUTTONDOWN Then
      Dim pt As New Point(m.LParam.ToInt32)
      If Me.IndexFromPoint(pt) = -1 Then
        Return
      End If
    End If
    MyBase.WndProc(m)
  End Sub

End Class