繁体   English   中英

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

[英]Panel Control Paint Event not working for User Control

我创建了一个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事件而不是显示完整图形的半图。

    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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM