[英]Why does this single line of code cause Visual Studio to crash?
使用一行代码,我可以使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 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;
}
}
}
但是,透明度并不“坚持”。 重定位控件时,例如使用此事件处理程序:
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错误出现的时候。 (实际上我没有立即注意到这个错误,所以隔离有问题的代码行是相当难以忍受的。)
public class TransparentPanel : System.Windows.Forms.Panel
{
protected override void OnPaintBackground(PaintEventArgs pe)
{
this.Invalidate(); //this is the offending line
}
}
这类似于无限循环。
当你重新绘制面板时,你的处理程序被调用...并且你告诉它使自己无效......这会导致重绘......它会调用你的处理程序......等等。
设计师失去了理智。 您不需要或想要在OnPaintBackground
控件无效,除非它是有条件的(仍然很少见)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.