namespace System.Windows.Forms
{
internal static class ControlExtension
{
///
/// Performs an action on a control after its handle has been created. If the control's handle has already been created, the action is executed immediately.
///
/// This control.
/// The action to execute.
public static void CallWhenHandleValid(this Control ctrl, Action action)
{
if (ctrl.IsHandleCreated)
{
action(ctrl);
}
else
{
LayoutEventHandler handler = null;
handler = (sender, e) =>
{
if (ctrl.IsHandleCreated)
{
ctrl.Layout -= handler;
action(ctrl);
}
};
ctrl.Layout += handler;
}
}
public static void EnableChildren(this Control ctl, bool enabled)
{
foreach (Control sub in ctl.Controls)
{
if (sub is ButtonBase || sub is ListControl || sub is TextBoxBase)
sub.Enabled = enabled;
sub.EnableChildren(enabled);
}
}
///
/// Gets the control in the list of parents of type T.
///
/// The based of the parent control to retrieve.
/// This control.
/// The parent control matching T or null if not found.
public static T GetParent(this Control ctrl) where T : class
{
Control p = ctrl.Parent;
while (p != null & !(p is T))
p = p.Parent;
return p as T;
}
///
/// Gets the top-most control in the list of parents of type T.
///
/// The based of the parent control to retrieve.
/// This control.
/// The top-most parent control matching T or null if not found.
public static T GetTopMostParent(this Control ctrl) where T : Control, new()
{
var stack = new System.Collections.Generic.Stack();
Control p = ctrl.Parent;
while (p != null)
{
stack.Push(p);
p = p.Parent;
}
while (stack.Count > 0)
if ((p = stack.Pop()) is T)
return p as T;
return null;
}
///
/// Gets the right to left property.
///
/// This control.
/// Culture defined direction of text for this control.
public static RightToLeft GetRightToLeftProperty(this Control ctrl)
{
if (ctrl.RightToLeft == RightToLeft.Inherit)
return GetRightToLeftProperty(ctrl.Parent);
return ctrl.RightToLeft;
}
///
/// Determines whether this control is in design mode.
///
/// This control.
/// true if in design mode; otherwise, false.
public static bool IsDesignMode(this Control ctrl)
{
if (ctrl.Parent == null)
return true;
Control p = ctrl.Parent;
while (p != null)
{
var site = p.Site;
if (site != null && site.DesignMode)
return true;
p = p.Parent;
}
return false;
}
}
}