ListViews call SelectedIndexChanged once for every item unselected and for every item selected. I need to call a function under these conditions:
- Only once when a single item is selected, even if multiple or other things were selected before.
- Once when multiple items are selected but only after the mouse has let up.
- Once after everything is unselected.
(In other words, the fewest amount of calls while still handling every selected item one way or another)
bool holdMouse = false;
bool clicked = false;
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (MouseButtons == MouseButtons.Left)
{
holdMouse = true;
}
else if(clicked)
{
clicked = false;
func();
}
}
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
if (holdMouse)
{
holdMouse = false;
func();
}
}
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
clicked = true;
}
private void func() { }
This does everything I need except when I deselect multiple things it calls the function once before everything is deselected. It calls it after the first thing is deselected.
"holdMouse" is used to prevent anything from happening while the user is dragging a selection. and "clicked" is used to make sure that the function is only called once when multiple things are deselected. Without that is calls it for each item that is deselected.
I've also tried the top answer from here: Catching Unselecting All in ListView -- SelectedIndexChanged Firing Twice But that only calls the function when an item is selected and not when things are deselected. I still have the problem that I need to call my function once after everything has been deselected.