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.
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 aBackColor
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);
}
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.