14

During the creation of my awesome Matching Game ;) I found a problem that is completely out of reach.

When the player chooses two labels with symbols on them I want to lock all the other labels for 4 seconds.

But when I do that, the forecolor of all the labels changes to grey and the symbols are visible. My question is - is there a method to change the ForeColor of a disabled label in visual c#?

The project is a WinForm application.

At the moment I set the color of a label in code this way:

label1.ForeColor = lable1.BackColor;

When the user clicks the label I change it to:

lable1.ForeColor = Color.Black;
Nathan Van Dyken
  • 342
  • 1
  • 8
  • 21
Mqati
  • 155
  • 1
  • 1
  • 5

2 Answers2

13

Just create your own label with a redefined paint event:

protected override void OnPaint ( System.Windows.Forms.PaintEventArgs e )
{
    if ( Enabled )
    {
        //use normal realization
        base.OnPaint (e);
        return;
    }
    //custom drawing
    using ( Brush aBrush = new SolidBrush( "YourCustomDisableColor" ) )
    {
        e.Graphics.DrawString( Text, Font, aBrush, ClientRectangle );
    }
}

Be careful with text format flags during text drawing.

4444
  • 3,541
  • 10
  • 32
  • 43
Allender
  • 604
  • 4
  • 10
  • For anybody else who tries to do this with a DateTimePicker: here is the solution http://stackoverflow.com/questions/1595481/datetimepicker-and-userpaint-text-and-button-missing – Breeze Mar 16 '17 at 15:30
11

Way simpler than trying to change the way Windows draws disabled controls is to simply set a flag when you want the Label to be effectively "disabled", and then check the value of that flag in your Click event handler method before taking whatever action you want. If the control has been "disabled", then don't take any action.

Something like this:

private bool labelDisabled = false;

private void myLabel_Click(object sender, EventArgs e)
{
    if (!labelDisabled)
    {
        this.ForeColor = SystemColors.ControlText;
    }
}

Also, note that you should always use the SystemColors instead of something like Color.Black.
If you hard-code specific color values, they will often conflict when the user customizes their default Windows theme. Raymond Chen discusses the perils of this in an article on his blog.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • 11
    Just a comment on the "always use SystemColors" advice - I'd say it should be always or never - as in, hardcode all colors for everything or none of them. Sometimes you want to control the look of things yourself instead of being a slave to the Windows theme. But don't mix them, that's when you get things conflicting. – Darrel Hoffman Dec 10 '13 at 22:02
  • 1
    Yes, definitely it's an "all or nothing" affair. But I take issue with your "slave to the Windows theme" phrasing. It helps if you think of it as "slave to your user's preferences." A rather good idea. – Cody Gray - on strike Feb 05 '16 at 14:10