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

kmo*_*ote 2 c# hang winforms visual-studio-2012

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

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

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

问题:这个bug应该报告给微软吗?如果是这样,怎么样?(我试图在MS Connect网站上提交错误,但显然他们只接受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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,透明度并不"坚持".重定位控件时,例如使用此事件处理程序:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Ed *_* S. 9

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

这类似于无限循环.

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

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

  • 那么我们可以让设计师去疯人院吗? (2认同)