Winforms - How to prevent the selection of list items

In WinForms, I have a loop running on a Listbox that selects Items.

During this time, I do not want the user to select items in this list with the mouse or the keys.

I looked at MyListbox.enabled = false, but it selects all the elements. Do not want this.

How to prevent the selection of items in the list?

+6
source share
4 answers

I also needed a read-only list, and finally, after much searching, I 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); } } } 
+7
source

Switch the Listbox.SelectionMode property to SelectionMode.None

Edit As I see it, setting SelectionMode.None deselects all previously selected elements and throws an exception if SetSelected is called in the list.

I think the desired behavior is impossible (without having to select elements using Enabled=false ).

+5
source

You might be lucky if you subclass 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 need to better hide information or class design, but this is the main functionality. There may be other methods that need to be redefined.

+1
source

Create an event handler that removes focus from the list and is signed by the Event GotFocus event handler. Thus, the user will never be able to select anything in the list. The following line of code does this using the built-in anonymous method:

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

* Edit : code explanation

+1
source

Source: https://habr.com/ru/post/901911/


All Articles