在Winforms中将CheckBox设为只读

I want to make CheckBox "readonly". I don't want do set Enable to false because I don't want it grayed out. setting AutoCheck to false is better but the CheckBox still blinks on a mouse click. How can I make it not react to the mouse visibly without making it look disabled?

The reason I want this is because making it disabled makes it look as if its not relevant but that is not the case. Setting AutoCheck to false is better, still, if I don't want the user to change it, it makes sense that it should not react to the mouse.

评论
加载中…
加载中…

You can inherit the CheckBox and create a ReadOnlyCheckBox with ReadOnly state like this:

public class ReadOnlyCheckBox : System.Windows.Forms.CheckBox
{
    [System.ComponentModel.Category("Behavior")]
    [System.ComponentModel.DefaultValue(false)]
    public bool ReadOnly { get; set; } = false;

    protected override void OnMouseEnter(EventArgs eventargs)
    {
        // Disable highlight when the cursor is over the CheckBox
        if (!ReadOnly) base.OnMouseEnter(eventargs);
    }

    protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mevent)
    {
        // Disable reacting (logically or visibly) to a mouse click
        if (!ReadOnly) base.OnMouseDown(mevent);
    }
}

这将禁用对鼠标单击的明显反应。

See my answer to a related question:
https://stackoverflow.com/a/55573352/10927863

点赞
评论