我正在创建一个应用程序来安排不同的任务。这些是通过在面板上绘制矩形来显示的。这必须是响应式的。所以我需要在每次尺寸变化时绘制并使其无效。当我达到计划面板的最大高度时,它会自动滚动。
问题是,当我捕获滚动条并开始滚动一段时间时,当我释放滚动条时,我的整个应用程序和计算机都会卡住。
这很可能是由于 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/