Redraw a Whole Control on Resize [C#]
When custom controls or Windows Forms controls like Panel are resized, only their newly exposed portions are redrawn. However, this behaviour sometimes does not provide the desired results (see fig. 1 below).
This example shows how to ensure redrawing of the whole control after resizing by setting the control's ResizeRedraw property.
Fig. 1. A partially redrawn control after resizing.
Redrawing the whole control on resize
The ResizeRedraw protected property defined in the Control class indicates, whether the control redraws itself when resized. To ensure redrawing of the whole control on resize set this property to true. This will usually be done in the constructor of a derived class.
[C#]public MyControl() { InitializeComponent(); ResizeRedraw = true; }
Alternatively, if you can not or don't want to create a derived class, set the property using reflection or simply call the Invalidate or Refresh method in the control's Resize event handler.
[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(); }
A sample control
The following is a code of a user control displaying an ellipse that stretches and shrinks when the control's size changes:
[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); } }
Whithout the ResizeRedraw statement, the control is redrawn only
partially and the result looks like in figure 1 above. When the
ResizeRedraw = true
statement is
included, the control is redrawn properly as shown in the
following figure 2.
Fig. 2. A properly redrawn control after resizing.
See also
- [C#] Set DoubleBuffered Property – explains how to avoid control flickering
- [C#] Reflection Examples – examples of how to use a dynamically loaded assembly
- [C#] Check Scrollbars Visibility – find out which scrollbars are visible
- ResizeRedraw Property – MSDN – indicates whether to redraw a control on resize
- Invalidate Method – MSDN – invalidates a control's content, so it is redrawn when idle
- Refresh Method – MSDN – immediately redraws a control
- Resize Event – MSDN – an event fired after control resizing
- OnPaintBackground Method – MSDN – paints a control's background