面板控件绘制事件不适用于用户控件

时间:2013-05-28 06:41:46

标签: c# winforms

我创建了一个Windows窗体用户控件,我拖动,在其中放置一个面板,在面板上我在Panel的Paint事件中绘制了图形。

private void pnlViewer_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.TranslateTransform(pnlViewer.AutoScrollPosition.X, pnlViewer.AutoScrollPosition.Y);
    e.Graphics.FillRectangle(Brushes.Black, Screen.PrimaryScreen.Bounds);
    //**draw Y Axis**
    int y;
    for (int i = 0; i <= 50; i++)
    {
        y = (i * cellHeight) + cellHeight;
        e.Graphics.DrawLine(new Pen(Color.FromArgb(50, 50, 50)),
                            new Point(0, y), new Point(pageWidth, y));
    }
    //**draw X Axis**
    int x;
    for (int i = 0; i < 50; i++)
    {
        x = (i * cellWidth) + ribbonWidth;
        e.Graphics.DrawLine(new Pen(Color.FromArgb(50, 50, 50)),
                            new Point(x, 0), new Point(x, pageHeight));
    }
    DrawWaveForm(e.Graphics); **// Here the actual data of graph will draw**
}

当我将此用户控件拖到WinForm上时,它会从Windows窗体中调用此用户控件的绘制事件,但在调用此事件时会显示图形但在一段时间后图形变为空白。

我尝试了Invalidate(true), Update(), Refresh()所有这些方法,但它们毫无用处。

实际上它显示了图形的一半,然后在下一个相同的绘制事件被触发后,它显示了我需要的完整图形,但实际上我想要第一个Paint事件而不是显示完整图形的半个图形。

1 个答案:

答案 0 :(得分:3)

    e.Graphics.DrawLine(new Pen(Color.FromArgb(50, 50, 50)),
                        new Point(0, y), new Point(pageWidth, y));

您没有在此代码中处理System.Drawing对象。也可能在其他代码中。这可以在很长一段时间内被忽视,垃圾收集器往往会隐藏问题。但是如果它运行得不够频繁,那么操作系统可能会因为使用如此多的GDI句柄而对你产生闷闷不乐,并且它不会让你的程序再创建它们。配额是10,000个句柄,非常大,但如果经常重新绘制则很容易消耗。例如,当你绘制一个不断更新的图表时。接下来会发生什么变化,介于异常和注意到程序不再正确绘制之间。

始终在绘制代码中使用 using 语句来避免此失败模式:

using (var pen = new Pen(Color.FromArgb(50, 50, 50))) {
    e.Graphics.DrawLine(pen, new Point(0, y), new Point(pageWidth, y));
}