How to loop through all controls in a Windows Forms form or how to find if a particular control is a container control?

前端 未结 4 1662
野趣味
野趣味 2021-02-19 21:38

I will tell my requirement. I need to have a keydown event for each control in the Windows Forms form. It\'s better to do so rather than manually doing it for all c

4条回答
  •  故里飘歌
    2021-02-19 22:31

    This is the same as Magnus' correct answer but a little more fleshed out. Note that this adds the handler to every control, including labels and container controls. Those controls do not appear to raise the event, but you may want to add logic to only add the handler to controls that accept user input.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            RegisterKeyDownHandlers(this);
        }
    
        private void RegisterKeyDownHandlers(Control control)
        {
            foreach (Control ctl in control.Controls)
            {
                ctl.KeyDown += KeyDownFired;
                RegisterKeyDownHandlers(ctl);
            }
        }
    
        private void KeyDownFired(object sender, EventArgs e)
        {
            MessageBox.Show("KeyDown fired for " + sender);
        }
    }
    

提交回复
热议问题