【发布时间】:2016-11-08 18:43:12
【问题描述】:
我有以下代码在我的 winform 上创建混合背景:
public partial class Aging : Form
{
protected override void OnPaintBackground(PaintEventArgs e)
{
using (var brush = new LinearGradientBrush(this.ClientRectangle,
Color.Transparent, Color.Transparent, LinearGradientMode.Vertical))
{
var blend = new ColorBlend();
blend.Positions = new[] { 0, 3 / 10f, 1 };
blend.Colors = new[] { Color.WhiteSmoke, Color.LightSteelBlue, Color.LightSteelBlue };
brush.InterpolationColors = blend;
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
}
结果是颜色背景从 LightSteelBlue 渐变为 WhiteSmoke:
问题是,如果我最小化屏幕,然后再最大化,应用程序将不再显示背景:
这是我收到的异常消息:
System.ArgumentException: Rectangle '{X=0,Y=0,Width=0,Height=0}' cannot have a width or height equal to 0.
at System.Drawing.Drawing2D.LinearGradientBrush..ctor(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
at AgingStatusDb.Aging.OnPaintBackground(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmEraseBkgnd(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg,
IntPtr wparam, IntPtr lparam)
我不是那么精明,也无法找出故障的根源。任何帮助将不胜感激。
【问题讨论】:
-
最小化时可能已经发生。最好在开始时添加宽度> 0 的检查.. 虽然不能在这里重现。但是错误提到了
Rectangle rect,而不是在您的代码中!?! -
嗯,它确实显示了背景,但它现在是失败的红十字会。并且将保持这种状态,一旦您的绘画代码崩溃,它将不会尝试再次运行它以避免异常风暴。您收到的异常消息非常好,您无法创建 0x0 像素的画笔。这很容易检查您的 OnPaintBackground() 方法,如果 CllientRectangle.Width 或 Height 为 0,则不执行任何操作。
-
仅检查零宽度或高度是不够的。您还应该在构造函数中设置
this.DoubleBuffered = true;。此外,您还需要设置this.SetStyle(ControlStyles.ResizeRedraw, true);以在调整表单大小时重绘表单。