简体   繁体   中英

c# Windows forms checkbox text disappears when control is disabled

I have a strange issue which I never noticed before. I have a checkbox on a form whose backcolor is web:black. My checkbox text is web:gold. Everything is fine except when that checkbox is not enabled. If I do

checkbox.Enabled = false;

then the text associated with that textbox doesn't show! I never noticed this before and now I need this but can't figure out how to fix it. Any ideas? Thanks

You can respond to the control's Paint event to perform custom rendering. Here's an example of a custom paint method, which just draws the text as normal when the checkbox is disabled:

private void checkBox1_Paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);

    if (!checkBox1.Enabled)
    {
        CheckBox checkbox = sender as CheckBox;

        int x = ClientRectangle.X + CheckBoxRenderer.GetGlyphSize(
            e.Graphics, CheckBoxState.UncheckedNormal).Width + 1;
        int y = ClientRectangle.Y + 1;

        TextRenderer.DrawText(e.Graphics, checkbox.Text, 
            checkbox.Font, new Point(x, y), checkbox.ForeColor, 
            TextFormatFlags.LeftAndRightPadding);
    }
}

(The exact X and Y coordinates may need tweaking depending on your font and other rendering characteristics.)

The Paint method can be set in the Properties window for the control - it's under Appearance in the Events section. You can double-click on the empty space to create an empty event handler and take you to the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM