简体   繁体   中英

Losing selecteditem when clicking on a empty space in a listbox

I want to ask you something, I have a listbox which contains multiple items. The listbox is set to MultiSimple as SelectionMode. So I can select multiple items.

It's working perfectly but if I click on a empty space in my listbox it causes to deselect the last item I selected. Or when there is no item selected it selects the first item.

How can I prevent the listbox to select/deselect items when I click on a empty space? (With the empty space I mean the space right under my items.)

Try this version of the ListBox control:

public class ListEx : ListBox {
  private const int WM_LBUTTONDOWN = 0x201;
  protected override void WndProc(ref System.Windows.Forms.Message m) {
    if (m.Msg == WM_LBUTTONDOWN) {
      Point pt = new Point(m.LParam.ToInt32());
      if (this.IndexFromPoint(pt) == -1) {
        return;
      }
    }
    base.WndProc(ref m);
  }
}

Converted from multisimple listbox. stop whitespace clicking from selecting deselecting last clicked item

Wow I recreated exactly what you did and the only option I came up with is trying to make you listbox smaller to eliminate white space. If the list in the box isn't a fixed size you could always make its size change based on the list size and set a maximum size before you need to scroll through it.

It's not the greatest solution but it seems to work.

It would look something like this.

public Form1(){
            InitializeComponent();
            if (listBox1.Items.Count < 6)
            {

                listBox1.Height = listBox1.Items.Count*12+9;
            }
            else
            {
                listBox1.Height = 69;
            }

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM