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

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

    You can do a recursive call to disable all of the controls involved. Then you have to enable your button and any parent containers.

     private void Form1_Load(object sender, EventArgs e) {
            DisableControls(this);
            EnableControls(Button1);
        }
    
        private void DisableControls(Control con) {
            foreach (Control c in con.Controls) {
                DisableControls(c);
            }
            con.Enabled = false;
        }
    
        private void EnableControls(Control con) {
            if (con != null) {
                con.Enabled = true;
                EnableControls(con.Parent);
            }
        }
    

提交回复
热议问题