奇怪的行为OnPaint / OnLayout

时间:2018-09-05 09:33:11

标签: c# .net winforms onpaint

我有一个网格和一个四边形。其中的网格布局四边形。

class Grid : System.Windows.Forms.Control
    {
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
        }

        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);

            int numControls = this.Controls.Count;

            if (numControls < 1)
            {
                return;
            }

            int size = this.Width / numControls;

            int i = 0;

            foreach (Control ctrl in this.Controls)
            {
                ctrl.Size = new Size(size, this.Height);
                ctrl.Location = new Point(i * size, 0);
                i++;
            }
        }
}

class Quad : System.Windows.Forms.Control
    {
        protected override void OnPaint(PaintEventArgs args)
        {
            base.OnPaint(args);

            Pen p = new Pen(new SolidBrush(Color.Black));

            int x = this.ClientRectangle.X;
            int y = this.ClientRectangle.Y;
            int w = this.ClientRectangle.Width;
            int h = this.ClientRectangle.Height;

            args.Graphics.DrawRectangle(p, x,y,w-1,h-1);
        }
    }

以及我拥有的表格

        this.quad1 = new Quad();
        this.SuspendLayout();

        grid1 = new Grid();
        grid1.Size = new Size(200, 200);

        for (int i = 0; i < 4; i++)
        {
            Grid grid_j = new Grid();
            for (int j = 0; j < 4; j++)
            {
                grid_j.Controls.Add(new Quad());
            }
            grid1.Controls.Add(grid_j);
        }

        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 261);
        this.Controls.Add(grid1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

protected override void OnLayout(System.Windows.Forms.LayoutEventArgs levent)
        {
             base.OnLayout(levent);

             this.grid1.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
             this.grid1.Location = new Point(0, 0);
        }

但是,这根本不起作用。一调整整个东西的大小 绘制疯狂的图案。

Crazy patterns

那是为什么?我尝试清除图形,但没有成功(我想它是在OnPaint之前自动清除的吗?)。

似乎添加“无效”调用可以解决问题:

foreach (Control ctrl in this.Controls)
            {
                ctrl.Size = new Size(size, this.ClientRectangle.Height-10);
                ctrl.Location = new Point(i * size, 0);
                ctrl.Invalidate();
                i++;
            }

这是正确的方法吗?另外,什么时候必须调用其他“更新”?

0 个答案:

没有答案