C# WinForm Resize Animation

Windows Forms

One of the great things about .NET Windows Forms are their flexibility. Developers can often allows users to easily resize Windows Forms. In fact, many times developers need to resize a Windows Form programmatically.

A very simple is example is the calculator application in Windows 7. If you switch between the different modes (Standard, Scientific, Programmer, Statistics), the calculator window resizes itself to fit in the buttons for that specific function.

What we will explore in this article is how to animate the size transformation, much like Windows Calculator does.

WinForm Animation

Animation in C# applications is an interesting subject that has been extensively covered. In this particular case we are going to pull together several concepts to acheive a practical use of animation in Windows Forms. (The word "practical" depending on each case of course).

To be more specific, animation in this case will be used to show a smooth transition between two different dimensions (width and length) of a Form. We are not concerned with animating images in this case.

Changing Form Dimensions

So let's say we have a Windows Form that has a width of 250 pixels and a height of 300 pixels (250 x 300). For some reason, we want to programmatically set the width and height to 200 x 200. The most obvious and direct way to do this would be:

this.Width = 200;
this.Height = 200;

Very clean and very simple, right?

Well in many cases this is enough. But of course, during run-time the change from 250 x 300 to 200 x 200 will be abrupt. If we want to animate a smooth transition between the different dimensions, then we have to take a different approach.

To give the appearance that the change is animated, we need to repeatedly decrease the width and height in small intervals until we reach the desired new dimensions.

So here is a very, very basic implementation of that concept:

while (this.Width > 200)
{
this.Width--;
Application.DoEvents(); //allow the Form to display its new size before
//the next iteration
}
while (this.Height > 200)
{
this.Height--;
Application.DoEvents();
}

That is the entire idea right there. Everything that follows from here is technical details of implementing that idea. Let's go over some of the points we need to address:

The code above resizes the width then the height. We want it to resize both at the same time.

The code should work in either direction (increasing or decreasing size) independently for width and for height.

How fast will this run? We want to make the animation run at a constant speed across multiple systems

This code is single-threaded, a smarter approach is to use a separate thread dedicated to UI updates.

Finally, we need to make the code work for any form (not just the one that "this" points to)