Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent controls from graying out when it is disabled

Tags:

c#

winforms

In winforms .net controls if we set Enabled property to false the control will be grayed out.

In this case it will become unreadable for many color combinations (because i am giving options to change color of a form for user at run time).

I can use ReadOnly property but it is available only to TextBox controls not for other controls like ComboBox, DateTimePicker etc.

I just wanted to know is there any option available so that i can prevent controls from graying out when it is disabled.

like image 687
Prasad Avatar asked Dec 05 '22 02:12

Prasad


1 Answers

This is a sad moment in most any usability study, seeing the subject banging away at the mouse and keyboard and not understanding why it doesn't work. But you can get it if you really want to. The trick is to put a picture box in front of the control that shows a bitmap of the controls in their previously enabled state. They'll never figure out they are clicking on a bitmap instead of the actual controls.

Best done with a Panel so you can easily disable controls as a group. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. And put the controls inside it that should be disabled. Everything else is automatic, just set the Enabled property to false and the user won't know what happened:

using System;
using System.Drawing;
using System.Windows.Forms;

class FakeItPanel : Panel {
    private PictureBox mFakeIt;

    public new bool Enabled {
        get { return base.Enabled; }
        set {
            if (value) {
                if (mFakeIt != null) mFakeIt.Dispose();
                mFakeIt = null;
            }
            else {
                mFakeIt = new PictureBox();
                mFakeIt.Size = this.Size;
                mFakeIt.Location = this.Location;
                var bmp = new Bitmap(this.Width, this.Height);
                this.DrawToBitmap(bmp, new Rectangle(Point.Empty, this.Size));
                mFakeIt.Image = bmp;
                this.Parent.Controls.Add(mFakeIt);
                this.Parent.Controls.SetChildIndex(mFakeIt, 0);
            }
            base.Enabled = value;
        }
    }

    protected override void Dispose(bool disposing) {
        if (disposing && mFakeIt != null) mFakeIt.Dispose();
        base.Dispose(disposing);
    }
}
like image 115
Hans Passant Avatar answered Dec 20 '22 09:12

Hans Passant