c# - 如何阻止 Paint 事件堆积

标签 c# winforms scroll paint onpaint

我正在创建一个应用程序来安排不同的任务。这些是通过在面板上绘制矩形来显示的。这必须是响应式的。所以我需要在每次尺寸变化时绘制并使其无效。当我达到计划面板的最大高度时,它会自动滚动。

问题是,当我捕获滚动条并开始滚动一段时间时,当我释放滚动条时,我的整个应用程序和计算机都会卡住。

这很可能是由于 onpaint 事件在每个小滚动上被调用并堆积起来,使应用程序挂起,直到它们全部完成。

现在我的问题是:我该如何解决这个问题?可能是通过防止多次调用绘制事件,但是如何实现呢?

paint事件调用的方法:

private void panelPlanning_Paint(object sender, PaintEventArgs e)
    {
        for (int i = 0; i < userList.Count; i++)
        {
            Label temp = new Label();
            temp.Text = userList[i].Text;
            temp.Width = panelUsers.Width;
            temp.Height = 50;
            temp.BorderStyle = BorderStyle.FixedSingle;
            temp.Location = new Point(0, i * 50);
            temp.TextAlign = ContentAlignment.MiddleCenter;
            panelUsers.Controls.Add(temp);

            foreach (FullTask task in taskList)
            {
                if (task.AssignedTo == userList[i].Text && task.StartDate != "" && task.DueDate != "")
                {
                    DateTime start = DateTime.ParseExact(task.StartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    DateTime end = DateTime.ParseExact(task.DueDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    Brush brush;
                    if (task.Priority == Enums.priorities[2])
                    {
                        brush = Brushes.Yellow;
                    }
                    else if (task.Priority == Enums.priorities[1])
                    {
                        brush = new SolidBrush(Color.FromArgb(255, 0, 80, 123));
                    }
                    else
                    {
                        brush = Brushes.Red;
                    }

                    panelPlanning.CreateGraphics().FillRectangle(brush, new Rectangle((start.Subtract(dtPickerStart.Value).Days + 1) * labelDaysWidth, i * 50, (end.Subtract(start).Days + 1) * labelDaysWidth, 25));
                }
            }
        }
    }

最佳答案

您将在每个绘画事件中添加新的标签控件。不要这样做:

      // Label temp = new Label();
      // temp.Text = userList[i].Text;
      // temp.Width = panelUsers.Width;
      // temp.Height = 50;
      // temp.BorderStyle = BorderStyle.FixedSingle;
      // temp.Location = new Point(0, i * 50);
      // temp.TextAlign = ContentAlignment.MiddleCenter;
      // panelUsers.Controls.Add(temp);

此外,使用参数提供的 e.Graphics 对象,而不是 CreateGraphics,

关于c# - 如何阻止 Paint 事件堆积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15904574/

相关文章:

javascript - 动画滚动脚本防止从外部链接访问本地 anchor 位置

css - ie6 中的布局、绝对位置问题

javascript - 滚动到 div 时显示它

c# - 如何使用 Oracle Entity Framework 支持强制使用 pascal 大小写?

c# - 桌面共享和聊天开源

winforms - 在 winforms 应用程序中以编程方式显示工具提示

c# - 我的 id 不为空,为什么会收到运行时错误?

c# - 如何使用周数和年份获取一周的开始和结束日期,并将这些日期插入 C# 中的 mysql 表中

c# - 如何使用 C# 在瀑布对话框中调用 QnA Maker?

c# - 整数和字符串上的空值,但它们已被分配