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

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

    Based on @pinkfloydx33's answer and the edit I made on it, I created an extension method that makes it even easier, just create a public static class like this:

    public static class GuiExtensionMethods
    {
            public static void Enable(this Control con, bool enable)
            {
                if (con != null)
                {
                    foreach (Control c in con.Controls)
                    {
                        c.Enable(enable);
                    }
    
                    try
                    {
                        con.Invoke((MethodInvoker)(() => con.Enabled = enable));
                    }
                    catch
                    {
                    }
                }
            }
    }
    

    Now, to enable or disable a control, form, menus, subcontrols, etc. Just do:

    this.Enable(true); //Will enable all the controls and sub controls for this form
    this.Enable(false);//Will disable all the controls and sub controls for this form
    
    Button1.Enable(true); //Will enable only the Button1
    

    So, what I would do, similar as @pinkfloydx33's answer:

    private void Form1_Load(object sender, EventArgs e) 
    {
            this.Enable(false);
            Button1.Enable(true);
    }
    

    I like Extension methods because they are static and you can use it everywhere without creating instances (manually), and it's much clearer at least for me.

提交回复
热议问题