使用Resize重绘整个控件
当自定义控件或windows fomrs 制件,如Panel,被重置,只有这些控件最新暴露的部分才会被重新绘制。然而,有时这些行为不会提供想要的结构(可见下面的图片1).
这个示例通过设置控件的ResizeRedraw属性,来演示如何确保重置后对整个控件进行重绘。
ResizeRedraw:定义在Control类中的受保护属性,该属性指示控件在调整大小时是否重绘自己。为了确保使用resize对整个控件进行重绘,设置resize属性为true。这个工作通常在继承类的构造函数中进行。
[C#] public MyControl() { InitializeComponent(); ResizeRedraw = true; }
或者,如果你不想要或不能创建一个继承类,可以用反射设置属性或简单地使用控件的resize事件调用Invalidate或Refresh函数:
[C#] using System.Reflection; public static void SetResizeRedraw(Control control) { typeof(Control).InvokeMember("ResizeRedraw", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, control, new object[] { true }); } [C#] myControl.Resize += new EventHandler(myControl_Resize); private void myControl_Resize(object sender, EventArgs e) { ((Control)sender).Invalidate(); }
示例控件
下面是用户控件的代码,当控件的尺寸变化时,用于显示椭圆形的扩大与缩小。
[C#] public partial class MyControl : UserControl { public MyControl() { InitializeComponent(); ResizeRedraw = true; } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); // draw a blue ellipse into the control area e.Graphics.FillEllipse(new SolidBrush(Color.Blue), 2, 2, ClientRectangle.Width - 4, ClientRectangle.Height - 4); } }
没有ResizeRedraw参数,控件仅部分进行重绘,结果就是像图片1;当ResizeRedraw = true
,控件就如下面图片所示可以正确重绘。