Search code examples
c#winformsloopspanelvisible

Why does toggling the Visibility of my Form disable my KeyDown event?


I am creating a grid of Panels at runtime and it is very ugly when it resizes due to being created by a loop. In order to "hide" this operation, I have called

this.Visible = false;

before my loop and

this.Visible = true;

after my loop.

 for (int i = 0; i < Size; i++)
        {
            for (int j = 0; j < Size; j++)
            {
                _panel = new Panel();
                _panel.Location = new Point((i * _panel.Size.Width) + ((i + 1) * _border), (j * _panel.Size.Height) + ((j + 1) * _border));                    
                this.Controls.Add(_panel);
            }
        }

The above code works GREAT however it only works once. After I toggle the visibility of my form, the KeyDown event no longer happens with I press a key.

Any ideas?


Solution

  • You should never change visibility for update operations. Rather use:

    this.SuspendLayout();
    
    // Do all the resizing here.
    
    this.ResumeLayout();