我能在Windows Forms表单中创建和显示多少个控件?

4
我正在开发一款C# Windows Forms应用程序。我知道太多控件会给用户带来可怕的体验,因此我会保持同时显示的控件数量较少(例如,如 Upper (reasonable) limit to number of user control instances 中所建议的那样),但一些控件可能会被隐藏(例如,使用选项卡或层)。
在一个表单上,是否存在可以显示的控件的绝对最大数量?如果有的话,是多少?

2
任何你喜欢的数字,如果你想要动态生成它们。 - Salah Akbari
1
嗨,这不是一个非常清晰的问题...或者说它只是奇怪地简单。你所说的适合表格是什么意思?简单的答案是取决于你的表格有多大以及控件有多大?这是假设你没有重叠...但这就是你所谈论的吗?当然,那将是一个几何问题而不是编程问题。 - Dave
7
你的应用程序用户数量应该控制在这个数量之内,以免过多导致混乱。 - dymanoid
3
如果你需要问这个问题,那就意味着你正在做某些错误的事情。 - SᴇM
1
如果你只是出于好奇而问这个问题,可以编写一些代码来循环创建控件,并查看何时会耗尽内存。如果你之所以问这个问题是因为担心在你正在开发的软件中可能会超过限制,那么你需要重新设计你的UI/UX。 - Diado
显示剩余3条评论
2个回答

15

实际上,有一个限制,虽然它没有硬编码且可配置 - 其默认值为 10,000 (为什么?)。

每个控件在操作系统中创建一个用户对象,而 Windows 中每个进程的默认活动用户对象数最大值为 10,000 - 因此一旦您尝试将第 10,001 个控件添加到表单中,应该会出现类型为 System.ComponentModel.Win32Exception 的异常,并显示以下消息:

Error creating window handle.

当然,没有用户希望看到带有 10,000 个控件的表单,因此除非您在某个地方发生了泄漏,否则不应该出现这种情况。(当然,我之所以知道它,只是因为我过去曾经有过这个泄漏 - 我的用户控件监听来自静态类的事件,并且没有在Dispose方法中取消挂钩,因此即使在它们从屏幕中清除之后,它们仍然存活...)

当您收到此异常时,请查看任务管理器的进程选项卡。 单击 视图 菜单,内部单击 选择列,选中 用户对象 复选框 (默认情况下不可见;这个事实可能会让我花费几个小时来理解我的泄漏) - 然后按该列进行排序。如果您在顶部看到您的应用程序,并且有 10,000 个用户对象 - 那么您就知道您的应用程序已经达到了控件的最大数量 - 这意味着您需要修复一个泄漏。

请注意,即使您从表单中删除控件,如果它们有其他引用,它们也不会被释放,如果您的应用程序运行足够长时间,您最终会遇到这种错误。

如果有人感兴趣,这里是我用于重新创建错误的代码(包括设计器代码)

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace UserObjectsLeak
{
    public partial class FrmUserObjectsLeak : Form
    {
        // This is used to keep references of the labels being added dynamically.
        static readonly List<Label> Labels = new List<Label>();

        public FrmUserObjectsLeak()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            for (var i = 0; i < 11000; i++)
            {
                var label = new Label()
                {
                    Text = i.ToString(),
                    Width = 50
                };
                Labels.Add(label);
                try
                {
                    panel1.Controls.Add(label);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    lblException.Text = ex.ToString();
                    return;
                }

                lblControlsCount.Text = (i).ToString();

                // Quick and dirty just to show the progress...
                Application.DoEvents();

                if (i % 500 == 0)
                {
                    // Remove all labels from the panel,
                    // keep only the reference in the list.
                    panel1.Controls.Clear();
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            Labels.Clear();
            lblControlsCount.Text = "";
            lblException.Text = "";
        }

        #region Designer code

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.btnStart = new System.Windows.Forms.Button();
            this.lblControlsCount = new System.Windows.Forms.Label();
            this.btnClear = new System.Windows.Forms.Button();
            this.panel1 = new System.Windows.Forms.FlowLayoutPanel();
            this.lblException = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(15, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(191, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Click the button to start adding controls";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 95);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "controls count:";
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(12, 49);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 2;
            this.btnStart.Text = "Start";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // lblControlsCount
            // 
            this.lblControlsCount.AutoSize = true;
            this.lblControlsCount.Location = new System.Drawing.Point(95, 95);
            this.lblControlsCount.Name = "lblControlsCount";
            this.lblControlsCount.Size = new System.Drawing.Size(0, 13);
            this.lblControlsCount.TabIndex = 3;
            // 
            // btnClear
            // 
            this.btnClear.Location = new System.Drawing.Point(98, 49);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(75, 23);
            this.btnClear.TabIndex = 5;
            this.btnClear.Text = "Clear";
            this.btnClear.UseVisualStyleBackColor = true;
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // panel1
            // 
            this.panel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
            this.panel1.Location = new System.Drawing.Point(226, 17);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(200, 148);
            this.panel1.TabIndex = 6;
            // 
            // lblException
            // 
            this.lblException.AutoSize = true;
            this.lblException.Location = new System.Drawing.Point(15, 179);
            this.lblException.Name = "lblException";
            this.lblException.Size = new System.Drawing.Size(0, 13);
            this.lblException.TabIndex = 7;
            // 
            // frmUserObjectsLeak
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(452, 308);
            this.Controls.Add(this.lblException);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.lblControlsCount);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "FrmUserObjectsLeak";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "User Objects Leak Demo";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.Label lblControlsCount;
        private System.Windows.Forms.Button btnClear;
        private System.Windows.Forms.FlowLayoutPanel panel1;
        private System.Windows.Forms.Label lblException;

        #endregion Designer code
    }
}

4
很高兴看到积极的回应。有些人在这个问题上过于抽象了。这是一个合理的问题。如果有人不熟悉动态创建组件,他们可能很难快速证明这一点。他们可能希望构建一个包含许多组件的大型表单,但不知道在完成之前是否会遇到硬限制。 - Creyke
2
@Creyke 我花了大约两天的时间找到问题所在,又花了半天的时间弄清楚为什么会出现这个问题以及如何解决它。如果我能帮助其他程序员节省这些时间,那么这个答案就值得我投入的时间,同样也值得提出这个问题的时间。 - Zohar Peled
2
错误信息是什么?(如果不明显,引用消息将有助于其他用户更轻松地找到答案。) - user202729
@user202729 我希望我能记得这件事。这是大约3年前发生的...我会尝试在我的电脑上重新创建这种情况来进行测试。 - Zohar Peled
@user202729 感谢您的评论。我已经重新创建了错误并更新了我的答案。 - Zohar Peled

0

实际上,如果从表单构造器中动态添加,则没有限制。为了进行实验,我添加了10万个标签和1万个带颜色的面板,尽管需要超过15分钟才能显示(PC:8GB RAM,SixCore 3.50 GHz CPU),但在显示表单后,没有性能问题(它消耗了30MB的RAM内存),也不会影响拖动表单。

然而,正如之前的评论所说(#Zohard Peled),如果表单已经被显示,则只能添加10,000个控件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接