tomfox66
tomfox66

Reputation: 329

Winforms - How to prevent Listbox item selection

In WinForms I occationally have a loop running over a Listbox selecting Items.

During that time I don't want the user to select items in that listbox with the mouse or keys.

I looked at MyListbox.enabled=false but it grays out all items. Dont't want that.

How to prevent selecting items in a Listbox?

Upvotes: 6

Views: 14843

Answers (4)

ItsMe
ItsMe

Reputation: 192

Create an event handler that removes focus from the Listbox and subscribe the handler to the Listbox's GotFocus event. That way, the user will never be able to select anything in the Listbox. The following line of code does that with an inline anonymous method:

txtBox.GotFocus += (object anonSender, EventArgs anonE) => { txtBox.Parent.Focus(); };

*Edit: code explanation

Upvotes: 2

Nathan
Nathan

Reputation: 1851

I too wanted a read only list box, and finally, after much searching, found this from http://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html:

public class ReadOnlyListBox : ListBox
{
    private bool _readOnly = false;
    public bool ReadOnly
    {
        get { return _readOnly; }
        set { _readOnly = value; }
    }

    protected override void DefWndProc(ref Message m)
    {
        // If ReadOnly is set to true, then block any messages 
        // to the selection area from the mouse or keyboard. 
        // Let all other messages pass through to the 
        // Windows default implementation of DefWndProc.
        if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E)
        && (m.Msg <= 0x0100 || m.Msg >= 0x0109)
        && m.Msg != 0x2111
        && m.Msg != 0x87))
        {
            base.DefWndProc(ref m);
        }
    }
}

Upvotes: 7

akatakritos
akatakritos

Reputation: 9858

You may have some luck if you sub class the ListBox and override the OnMouseClick method:

public class CustomListBox : ListBox
{
    public bool SelectionDisabled = false;

    protected override void OnMouseClick(MouseEventArgs e)
    {
        if (SelectionDisabled)
        {
            // do nothing.
        }
        else
        {
            //enable normal behavior
            base.OnMouseClick(e);
        }
    }
}

Of course you may want to do better information hiding or class design, but thats the basic functionality. There may be other methods you need to override too.

Upvotes: 1

Khh
Khh

Reputation: 2571

Switch the Listbox.SelectionMode property to SelectionMode.None

Edit As i see setting to SelectionMode.None deselects all previously selected items and throws an exception if SetSelected is called on the Listbox.

I think the desired behaviour is not possible (without wanting to gray out the items with Enabled=false).

Upvotes: 6

Related Questions