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

后端 未结 5 1525
孤街浪徒
孤街浪徒 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:13

    I have corrected @coloboxp answer, first you must enable all parents:

        public static void Enable(this Control con, bool enable)
        {
            if (con != null)
            {
                if (enable)
                {
                    Control original = con;
    
                    List parents = new List();
                    do
                    {
                        parents.Add(con);
    
                        if (con.Parent != null)
                            con = con.Parent;
                    } while (con.Parent != null && con.Parent.Enabled == false);
    
                    if (con.Enabled == false)
                        parents.Add(con); // added last control without parent
    
                    for (int x = parents.Count - 1; x >= 0; x--)
                    {
                        parents[x].Enabled = enable;
                    }
    
                    con = original;
                    parents = null;
                }
    
                foreach (Control c in con.Controls)
                {
                    c.Enable(enable);
                }
    
                try
                {
                    con.Invoke((MethodInvoker)(() => con.Enabled = enable));
                }
                catch
                {
                }
            }
        }
    

提交回复
热议问题