How to disable all controls on the form except for a button?

后端 未结 5 1523
孤街浪徒
孤街浪徒 2020-12-13 21:17

My form has hundreds of controls: menus, panels, splitters, labels, text boxes, you name it.

Is there a way to disable every control except for a single button?

5条回答
  •  醉酒成梦
    2020-12-13 22:11

    When you have many panels or tableLayoutPanels nested the situation becomes tricky. Trying to disable all controls in a panel disabling the parent panel and then enabling the child control does not enable the control at all, because the parent (or the parent of the parent) is not enabled. In order to keep enabled the desired child control I saw the form layout as a tree with the form itself as the root, any container or panel as branches and child controls (buttons, textBoxes, labels, etc.) as leaf nodes. So, the main goal is to disable all nodes within the same level as the desired control, climbing up the control tree all the way to the form level, stablishing a path of enabled controls so the child one can work:

    public static void DeshabilitarControles(Control control)
    {
        if (control.Parent != null)
        {
            Control padre = control.Parent;
            DeshabilitarControles(control, padre);
        }
    }
    
    private static void DeshabilitarControles(Control control, Control padre)
    {
        foreach (Control c in padre.Controls)
        {
            c.Enabled = c == control;
        }
        if (padre.Parent != null)
        {
            control = control.Parent;
            padre = padre.Parent;
            DeshabilitarControles(control, padre);
        }
    }
    
    public static void HabilitarControles(Control control)
    {
        if (control != null)
        {
            control.Enabled = true;
            foreach (Control c in control.Controls)
            {
                HabilitarControles(c);
            }
        }
    }
    

提交回复
热议问题