How to make a CheckBox unselectable?

后端 未结 10 2165
慢半拍i
慢半拍i 2021-01-07 16:34

I was wondering how you make a CheckBox unselectable in c#? I thought it would be something like SetSelectable (false) or something but I can\'t seem to see th

相关标签:
10条回答
  • 2021-01-07 17:00

    You can set AutoCheck property to false.

    0 讨论(0)
  • 2021-01-07 17:04

    For disabling all the checkboxes in a CheckedListBox

    for (int i = 0; i < checkedListBoxChecks.Items.Count; i++)
    {
       checkedListBoxChecks.SetItemChecked(i, true);
       //checkedListBoxChecks.Enabled = false;
       this.checkedListBoxChecks.SetItemCheckState(i, CheckState.Indeterminate);                  
    }
    
    
    private void checkedListBoxChecks_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.CurrentValue == CheckState.Indeterminate)
        {
            e.NewValue = e.CurrentValue;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 17:04

    In order to make a more read-only behavior:

    • Disable highlight when the cursor is over the CheckBox
    • Disable reacting (logically or visibly) to a mouse click
    • Have tooltips enabled

    We can inherit the CheckBox class (similar to Haris Hasan's answer but with some improvements):

    public class ReadOnlyCheckBox : CheckBox
    {
        [System.ComponentModel.Category("Behavior")]
        [System.ComponentModel.DefaultValue(false)]
        public bool ReadOnly { get; set; } = false;
    
        protected override void OnMouseEnter(EventArgs e)
        {
            // Disable highlight when the cursor is over the CheckBox
            if (!ReadOnly) base.OnMouseEnter(e);
        }
    
        protected override void OnMouseDown(MouseEventArgs e)
        {
            // Disable reacting (logically or visibly) to a mouse click
            if (!ReadOnly) base.OnMouseDown(e);
        }
    
        protected override void OnKeyDown(KeyEventArgs e)
        {
            // Suppress space key to disable checking/unchecking 
            if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
        }
    }
    
    0 讨论(0)
  • 2021-01-07 17:07

    This code worked for me:

    public class CtrlCheckBoxReadOnly : System.Windows.Forms.CheckBox
    {
        [Category("Appearance")]
        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        public bool ReadOnly { get; set; }
    
        protected override void OnClick(EventArgs e)
        {
            if (!ReadOnly) base.OnClick(e);
        }
    }
    
    0 讨论(0)
提交回复
热议问题