4

Under Windows Forms technology, I'm subclassing the Form class and overriding the OnControlAdded event invocator, my intention is that every control that is added to the control collection of my form, set its Control.BackColor property to Color.Transparent value regardless of the default color inheritance when a control is added into my Form.

However, as you probably know, some controls such as ListView does not accept transparency and when attempting to set the Color.Transparent value, a System.ArgumentException will be thrown telling you can set transparent color.

Then, my question is:

In C# or VB.NET, which would be the proper way (maybe with Reflection, or maybe calling a Win32 function) to determine at runtime whether a control allows a transparent back color (Color.Transparent)?... instead of handling the specified exception or classifying the control types in a switch case, for example.

ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • 1
    While this doesn't answer your question directly, it may contain something useful for you: https://stackoverflow.com/questions/9358500/making-a-control-transparent – Andrew Mortimer Feb 21 '18 at 11:17

1 Answers1

5

To check if a control supports Transparent back color, You can use GetStyle method of the control by passing ControlStyles.SupportsTransparentBackColor flag as input.

The result is a bool value which tells you if the controls supports the style.

If true, the control accepts a BackColor with an alpha component of less than 255 to simulate transparency. Transparency will be simulated only if the UserPaint bit is set to true and the parent control is derived from Control.

The method is protected so it's accessible in derived classes.

If you are going to use it from outside of a control, you need to call it by reflection:

public static bool GetControlStyle(Control control, ControlStyles flags)
{
    Type type = control.GetType();
    BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    MethodInfo method = type.GetMethod("GetStyle", bindingFlags);
    object[] param = { flags };
    return (bool)method.Invoke(control, param);
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398