I was searching for a solution to this problem, but to prevent the last item in the listbox from becoming selected when clicking on the blank space. my problem is slightly different but has the same solution that I have come up with which works for me.
Although I am using powershell and not c#, I am still utilizing the windows forms listbox control so I think the idea will be applicable.
Also, I couldn't find any discussions of this problem specifically dealing with powershell when I was searching for a solution, so I wound up here.
so I created a variable, maxY, and multiplied the number of list items by the itemheight.
next, at the beginning of the mouse_up event, I just check if the Y location from the mouse click is less than the maxY variable. if true, select the item and run your code, if not, do nothing.
I can only provide a code sample in powershell, but I think the idea is portrayed.
$listbox.add_MouseUP({
$maxY = $this.items.count * $this.itemHeight
if ($_.y -le $maxY) {
$this.SelectedIndex = $this.IndexFromPoint($_.X, $_.y)
#do stuff here
}
else {
$this.clearselection()
}
}
This will clear all selections if clicking on blank space, but will also prevent an item from being selected when clicking on blank space.