C# Programming > Windows Forms

 

Independent Resizing

Let's tackle the first two points first, since they are simple programming logic. To make the width and height resize independently and in increasing or decreasing direction, we need some helper functions.

IsWidthOff - This function takes the current Form width, the width we want to ultimately reach, and the size of each incremental step. The C# function then returns if the width still needs to be adjusted.

IsHeightOff - Exact same thing, but for the height.

Notice right away that there is no need for two functions since they both do the same thing. The reason for two separate functions are to make the code super-clear (since we are trying to learn here, right?).

With those two functions we can write the following code:

bool widthOff = IsWidthOff(this.Width, targetWidth, xStep);
bool heightOff = IsHeightOff(this.Height, targetHeight, yStep);

while (widthOff || heightOff)
{
     if (widthOff)
         this.Width += xStep;

     if (heightOff)
         this.Height += yStep;

     widthOff = IsWidthOff(this.Width, targetWidth, xStep);
     heightOff = IsHeightOff(this.Height, targetHeight, yStep);

     Application.DoEvents();
}

Threading the Animation

Running the animation source code in another thread is only slightly tricky. The main pitfall to avoid are improper cross-thread calls. Since the thread executing the loop is not part of the thread executing the form, you cannot directly change the Form object.

The solution is to use delegates. We have a pretty good article that covers cross-thread calls so I won't ruin it by reposing the content here. Check out the article and pay extra attention on how to pass variables/parameters between threads. This is important since we are going to need to pass to parameters: the Form to transform, and the target size.

Animation Speed

For this I am going to refer again to another one of our articles: the WinForm animation article. The part you want to read carefully is the Frames per Second section. (Don't think first-person video game FPS, that's similar but not what we are talking about).

The short version of it is that the loop doesn't executive the code inside the loop on every iteration. It only executes when a minimum amount of time has occured between "frames". The time is measured using the StopWatch class which uses some fancy API calls. Bottom line is, with some simple math, we can get a fairly constant animation speed no matter how fast the computer executing the code is.

The Sample Code

Of course, this is all getting fairly complicated, so I wrapped it all together nicely under a static class that you can download at the bottom of the page. You can effectively drop the code in your C# projects and programmatically animate WinForm size transformations. So download the code, it is not that bad.

Page 1
<< Animation Concept

Back to C# Article List