在WinForms中,我偶尔会在选择项目的列表框中运行一个循环。Winforms - 如何防止列表框项目选择
在此期间,我不希望用户使用鼠标或键在列表框中选择项目。
我看着MyListbox.enabled = false,但它灰色的所有项目。不要那样。
如何防止在列表框中选择项目?
在WinForms中,我偶尔会在选择项目的列表框中运行一个循环。Winforms - 如何防止列表框项目选择
在此期间,我不希望用户使用鼠标或键在列表框中选择项目。
我看着MyListbox.enabled = false,但它灰色的所有项目。不要那样。
如何防止在列表框中选择项目?
交换机的Listbox.SelectionMode属性SelectionMode.None
编辑 我看到设置SelectionMode.None取消选择所有之前选择的项目,并抛出一个异常,如果SetSelected被称为在列表框。
我认为所需的行为是不可能的(不想灰掉与Enabled=false
项目)。
你可能有一些运气,如果你的子类列表框和覆盖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);
}
}
}
您可能希望做的更好信息隐藏或类设计课程,但多数民众赞成的基本功能。也可能有其他方法需要重写。
我也想要一个只读列表框,最后,经过一番搜索,发现这个从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);
}
}
}
创建一个事件处理程序,从列表框中删除焦点和订阅的处理程序列表框的的GotFocus事件。这样,用户将永远无法在列表框中选择任何内容。以下代码行使用内联匿名方法:
txtBox.GotFocus + =(object anonSender,EventArgs anonE)=> {txtBox.Parent.Focus(); };
*编辑:代码解释
如果我这样做,我的循环这是在那个时候运行将无法选择项目。记住我想循环选择项目,但不是用户。 – tomfox66
这适用于我的场景:我不希望用户能够检查项目,但必须能够以编程方式检查它们。谢谢。 –