Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms - How to prevent Listbox item selection

Tags:

c#

.net

winforms

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?

like image 251
tomfox66 Avatar asked Nov 19 '11 22:11

tomfox66


4 Answers

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);
        }
    }
}
like image 57
Nathan Avatar answered Oct 19 '22 03:10

Nathan


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).

like image 27
Khh Avatar answered Oct 19 '22 02:10

Khh


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

like image 2
ItsMe Avatar answered Oct 19 '22 02:10

ItsMe


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.

like image 1
akatakritos Avatar answered Oct 19 '22 01:10

akatakritos