【问题标题】:The program exited with code-1073741819 (0xc0000005) 'Access violation'程序以代码 1073741819 (0xc0000005) '访问冲突'退出
【发布时间】:2016-06-20 06:30:40
【问题描述】:

我正在使用graphicPath 在panel1 中绘制点和线。代码如下:

private void panel1_Paint_1(object sender, PaintEventArgs e)
    {                 
        Graphics G = e.Graphics;
        GraphicsPath gp = new GraphicsPath();

        foreach (var line in tockeKoordinate)
        {
            gp.AddLine((float) (line.startX), (float) (line.startY), (float) (line.endX), (float) (line.endY));
            gp.CloseFigure();
        }
        var rect = gp.GetBounds();
        var scale = Math.Min(1f * (int)(panel1.ClientSize.Width) / rect.Width,
                               1f * (int)(panel1.ClientSize.Height) / rect.Height);          

        using (Pen pen = new Pen(Color.Black, 0.0001f))
                {
                    G.SmoothingMode = SmoothingMode.AntiAlias;
                    G.Clear(Color.White);
                    G.TranslateTransform(0, +panel1.ClientSize.Height);
                    G.ScaleTransform(scale, -scale);
                    G.TranslateTransform(-rect.X, -rect.Y);
                    G.DrawPath(pen, gp);
               }
        if(checkBox1.Checked)
        {
            gp.ClearMarkers();
            foreach (var line2 in tockeZelene)
            {
                gp.AddLine((float)(line2.startX), (float)(line2.startY), (float)(line2.endX), (float)(line2.endY));
                gp.CloseFigure();
            }

            using (pen2);
            {
                G.DrawPath(pen2, gp);   <--- access violation here
            }  
        }      
    }

基本上我有两个ListsTockekoordinatetockeZelena。第一个包含所有点,第二个包含大约 30% 的第一个点,我想使用我的 pen2 将其绘制为绿色,该笔在开始时已初始化。

假设checkbox1被选中,我运行所有点以获得矩形GetBounds,所以我可以用点坐标缩放panel1。

然后 checkbox1.checked 部分来了,应用程序在标记的行退出。

有谁知道是什么原因造成的?或者至少知道如何设置 VS 以向我显示有关所述错误的更多信息?

【问题讨论】:

    标签: c# graphics path draw


    【解决方案1】:

    下面这行有点可疑..

     using (pen2); //<--this one!!!
     {
          G.DrawPath(pen2, gp);
     }
    

    首先,DrawPath 将始终抛出异常,因为您将使用已处置的对象。要解决这个问题,请删除分号...

    using (pen2)
     {
          G.DrawPath(pen2, gp);
     }
    

    其次,pen2 是什么?谁在使用它?如果它正被另一个线程使用,则会发生访问冲突,因为您对 pen2 的使用不是线程安全的。

    最后,不要在 Paint 事件中处理全局对象 (pen2),除非您一直在重新创建它,因为每次您的控件需要重绘其表面时都会触发此事件。这意味着,您的控件第二次需要重绘时,将使用已处置的对象。

    【讨论】:

    • 是的,删除分号会有所帮助,但是将 pen2 声明放在 paint 方法中就可以了。
    猜你喜欢
    • 2022-06-10
    • 2015-10-18
    • 1970-01-01
    • 2018-11-10
    • 2020-06-13
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多