5

I created one Windows Forms User Control, I drag, dropped a panel inside it and over the panel I drew the graph in the Paint event of Panel.

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**
}

When I drag this user control onto a WinForm, it calls this paint event of User Control from windows form, but while calling to this event the graph is shown but after some time the graph becomes blank.

I tried Invalidate(true), Update(), Refresh() all such methods but they were of no use.

Actually it shows half of the graph over form and after next the same paint event is fired then it shows the full graph that I require, but actually I want on first Paint event instead of half graphs showing the full graph.

4

1 回答 1

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));
}
于 2013-05-28T11:29:52.060 回答