2011-11-19 61 views
6

在WinForms中,我偶尔会在选择项目的列表框中运行一个循环。Winforms - 如何防止列表框项目选择

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

我看着MyListbox.enabled = false,但它灰色的所有项目。不要那样。

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

回答

5

交换机的Listbox.SelectionMode属性SelectionMode.None

编辑 我看到设置SelectionMode.None取消选择所有之前选择的项目,并抛出一个异常,如果SetSelected被称为在列表框。

我认为所需的行为是不可能的(不想灰掉与Enabled=false项目)。

+0

如果我这样做,我的循环这是在那个时候运行将无法选择项目。记住我想循环选择项目,但不是用户。 – tomfox66

+0

这适用于我的场景:我不希望用户能够检查项目,但必须能够以编程方式检查它们。谢谢。 –

1

你可能有一些运气,如果你的子类列表框和覆盖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); 
     } 
    } 
} 

您可能希望做的更好信息隐藏或类设计课程,但多数民众赞成的基本功能。也可能有其他方法需要重写。

7

我也想要一个只读列表框,最后,经过一番搜索,发现这个从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); 
     } 
    } 
} 
+0

DefWndProc的神奇令人惊叹! +1 – Neolisk

+0

完美地工作 - 我会假设你会想要一个ReadOnlyListBox默认_readOnly为true,你会不会? – Mani5556

1

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

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

*编辑:代码解释