How to make a CheckBox unselectable?

后端 未结 10 2163
慢半拍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: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);
        }
    }
    

提交回复
热议问题