[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Redraw a form whenever it resizes in C#

example

This example shows how you can redraw a form whenever it grows or shrinks.

When a form grows larger, parts of it are exposed and the form raises a Paint event so the form can redraw those parts. Unfortunately the event handler can only draw on the newly exposed areas. The Paint event is also not raised when the form shrinks because no new areas are exposed. Neither of these is a problem if you are drawing something simple, but it can produce strange results if the drawing sizes itself to fit the form. (See the picture.)

To handle this, use code to set the form's ResizeRedraw property to true. Then whenever the form resizes, it raises a Paint event. (Strangely this property isn't visible in the Properties window at design time, so you have to set it in code.)

This example uses the following code to set ResizeRedraw to true or false when you check and uncheck a CheckBox, so you can compare the program's behavior with and without redrawing.

// Turn ResizeRedraw on or off. private void chkResizeRedraw_CheckedChanged(object sender, EventArgs e) { this.ResizeRedraw = (chkResizeRedraw.Checked); }

The program uses the following code to draw a diamond whenever the form raises its Paint event.

// Draw a diamond that fits the form. private void Form1_Paint(object sender, PaintEventArgs e) { Point[] pts = { new Point((int)(this.ClientSize.Width / 2), 0), new Point(this.ClientSize.Width, (int)(this.ClientSize.Height / 2)), new Point((int)(this.ClientSize.Width / 2), this.ClientSize.Height), new Point(0, (int)(this.ClientSize.Height / 2)), }; e.Graphics.DrawPolygon(Pens.Red, pts); }

This code creates an array holding points that define the diamond. It then uses e.Graphics.DrawPolygon to draw the diamond.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.