Winforms – 如何防止列表框项目选择

在WinForms中,我在一个选择Items的Listbox上运行循环。

在此期间,我不希望用户使用鼠标或键选择该列表框中的项目。

我查看了MyListbox.enabled = false,但它会显示所有项目。 不要那样。

如何防止在列表框中选择项目?

我也想要一个只读列表框,最后经过大量搜索后,从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); } } } 

将Listbox.SelectionMode属性切换到SelectionMode.None

编辑我看到设置为SelectionMode.None取消选择所有以前选择的项目,如果在列表框上调用SetSelected,则抛出exception。

我认为不可能实现所需的行为(不希望使用Enabled=false使项目变灰)。

如果您对ListBox进行子类并重写OnMouseClick方法,那么您可能会有一些运气:

 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); } } } 

当然,您可能希望做更好的信息隐藏或类设计,但这就是基本function。 您可能还需要覆盖其他方法。

创建一个事件处理程序,从Listbox中删除焦点,并将处理程序订阅到Listbox的GotFocus事件。 这样,用户将永远无法在列表框中选择任何内容。 以下代码行使用内联匿名方法:

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

*编辑 :代码说明