简体   繁体   English

如何确定控件是否允许C#透明?

[英]How to determine whether a control allows transparency in C#?

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. 在Windows Forms技术下,我是Form类的子类并重写OnControlAdded事件调用器 ,我的意图是每个控件都添加到我的表单的控件集合中,将其Control.BackColor属性设置为Color.Transparent值,而不管将控件添加到我的表单中时的默认颜色继承。

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. 但是,您可能知道,某些控件(如ListView不接受透明度,并且在尝试设置Color.Transparent值时,将抛出System.ArgumentException告知您可以设置透明颜色。

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. 在C#或VB.NET中,这将是正确的方式(可能使用Reflection,或者可能调用Win32函数)在运行时确定控件是否允许透明的背面颜色( Color.Transparent )?...而不是处理例如,指定异常或在switch案例中对控件类型进行分类。

To check if a control supports Transparent back color, You can use GetStyle method of the control by passing ControlStyles.SupportsTransparentBackColor flag as input. 要检查控件是否支持Transparent背面颜色,可以通过传递ControlStyles.SupportsTransparentBackColor标志作为输入来使用GetStyle方法。

The result is a bool value which tells you if the controls supports the style. 结果是一个bool值,它告诉您控件是否支持该样式。

If true , the control accepts a BackColor with an alpha component of less than 255 to simulate transparency. 如果为true ,则控件接受具有小于255的alpha分量的BackColor以模拟透明度。 Transparency will be simulated only if the UserPaint bit is set to true and the parent control is derived from Control. 仅当UserPaint位设置为true且父控件派生自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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM