问题
My usercontrol inherits System.Windows.Forms.Control
class. The following link describes the "Visible" property of control
Control.Visible
As per the above link, if control is present in inactive tab, then Control.Visible will return false even though we did not set it programmatically
Question: How do I identify whether visibility was disabled by user or other controls?
Note:
I tried overriding the Visible
property of Contorl
but it's not overridable.
Explanation
If my control is present in unselected tab, then Control.Visible returns false. If the user wants to draw the control (export) in a Bitmap
or something else, I need to determine the visibility of child controls too. Since my control is not visible, there is no reliable way available to determine the visibility of child controls
回答1:
All controls in windows forms internally maintain their state. Visibility is also one of the things they maintain in state. Because it helps to identify why visibility of the control was changed.
Control.Visible
will return false if there is a control above your control or parent of your control is hidden. But value of Visible property in state will be false only if user set it to false.
Code:
//Method to ensure the visibility of a control
public bool DetermineVisibility(Control control)
{
//Avoid reflection if control is visible
if (control.Visible)
return true;
//Find non-public GetState method of control using reflection
System.Reflection.MethodInfo GetStateMethod = control.GetType().GetMethod("GetState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//return control's visibility if GetState method not found
if (GetStateMethod != null)
//return visibility from the state maintained for control
return (bool)(GetStateMethod.Invoke(control, new object[] { 2 }));
return false;
}
来源:https://stackoverflow.com/questions/27596529/how-to-identify-whether-visibility-of-the-control-is-changed-by-user-or-not