How to identify whether visibility of the control is changed by user or not?

后端 未结 1 399
误落风尘
误落风尘 2021-01-28 17:11

My usercontrol inherits System.Windows.Forms.Control class. The following link describes the \"Visible\" property of control Control.Visible

1条回答
  •  醉梦人生
    2021-01-28 17:27

    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;
            }
    

    0 讨论(0)
提交回复
热议问题