Wednesday, December 23, 2009

Customizing the disabled look of a RichTextBox in winforms

When setting the .Enabled property of a control to false, it renders it with the disabled color of the operating system. Sometimes you might just want a different look.

In order to accomplish this in a winform you need to perform a small workaround. If not you will end up with a blinking cursor in the control. Here’s an example in the form of an extension method.

public static class MyExtensions
{
public static void Disable( this Control control, Control focusTarget )
{
control.TabStop = false;
control.BackColor = Color.DimGray;
control.Cursor = Cursors.Arrow;
control.Enter += delegate { focusTarget.Focus(); };
}
}

In order for this to work you need to pass in another control which can receive focus. This could be a label or some other control on the form.

You would also need to create an Enable method and add some logic to remember the previous background color as well as set the correct Cursor state.