为什么这一行代码会导致Visual Studio崩溃?

时间:2014-05-29 16:44:35

标签: c# winforms visual-studio-2012 hang

使用一行代码,我可以使VS2012始终崩溃。 (通过"崩溃"我的意思是当我点击Build时,Visual Studio无限期挂起,我必须从任务管理器中删除它。)这里是代码(在自定义用户控件中) :

public class TransparentPanel : System.Windows.Forms.Panel
{
    protected override void OnPaintBackground(PaintEventArgs pe)
    {
        this.Invalidate(); //this is the offending line
    }
}

要重现此问题,请根据上述代码创建一个控件并将其添加到Windows窗体中;然后尝试Build Solution。 " Build build ..."将显示在状态栏中,然后VS将立即永久冻结。我使用 devenv / log 尝试了troubleshooting,但活动日志没有显示任何错误或警告。所以我的问题是,为什么这个代码对C#编译器来说是致命的?(它在IDE中也会引起问题。例如,在添加这个透明控件之后,只要表单设计器是,“属性”窗格就会冻结打开)。

附带问题:这个bug应该报告给微软吗?如果是这样,怎么样? (我试图在the MS Connect site上提交错误,但显然他们只接受VS2013的错误。)


[如果你想知道为什么我试图使用那条线的背景,请继续阅读。]

我为应用程序创建了一个自定义(Windows窗体)控件。 (我试图用部分透明的图像创建一个控件,其位置可以通过鼠标交互来改变。) 我使用了下面的代码,它给了我一张我正在寻找的透明度的图像(在面板上):

public class TransparentPanel : System.Windows.Forms.Panel
{
    public Image Image { get; set; }

    protected override void OnPaint(PaintEventArgs pe)
    {
        Rectangle rect = new Rectangle(this.Location, this.Size);
        if (Image != null)
            pe.Graphics.DrawImage(Image, this.DisplayRectangle);
    }

    protected override void OnPaintBackground(PaintEventArgs pe)
    {
        //this.Invalidate();
        Brush brush = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
        pe.Graphics.FillRectangle(brush, pe.ClipRectangle);
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT       
            return cp;
        }
    }
}

然而,透明度并没有“坚持”#34;重定位控件时,例如使用此事件处理程序:

    private void transparentPanel1_MouseClick(object sender, MouseEventArgs e)
    {
        int y = this.transparentPanel1.Location.Y ;
        int x = this.transparentPanel1.Location.X ;
        this.transparentPanel1.Location = new System.Drawing.Point(x-5, y-5);
    }

...控件的透明部分保留了与第一次绘制时相同的背景。 (只有在其后面放置了另一个控件才能看到。抱歉,很难描述。)所以我试图使用Invalidate()来重新绘制控件,因此,重新绘制透明部分以匹配后面的任何内容搬迁后的控制。这是VS错误出现的时候。 (实际上我没有立即注意到这个错误,所以隔离有问题的代码行是相当难以忍受的。)

1 个答案:

答案 0 :(得分:9)

public class TransparentPanel : System.Windows.Forms.Panel
{
    protected override void OnPaintBackground(PaintEventArgs pe)
    {
        this.Invalidate(); //this is the offending line
    }
}

这类似于无限循环。

当你重新绘制面板时,你的处理程序被调用...并且你告诉它使自己无效......这会导致重绘......它会调用你的处理程序......等等。

设计师失去了理智。您不需要或想要在OnPaintBackground内使控件无效,除非它是有条件的(仍然很少见)。

相关问题