Center align on windows forms

I have been to a number of companys and seen a number of times, forms layouts that contain a centre aligned header, the sort of which, you would find on a web page. Eveytime I see this I come across a Form_Resize event handler which recalculates the location evrytime the form changes size. The code has often been complicated by the fact that people have things stuck to the side of their window.

A little known fact it seems is that this effect can be achieved without code in .NET 2.0 with the use of anchors. Or more importantly the non use of them. By default controls are anchored to the top left of the form which means when the form size is changed, their distance from the top left side of the for remains constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized. The clever trick with this is when you centre a control on the form horizontally, vertically or both, turning off the anchor in a direction will keep the control centred in that direction when resizing. This can be usefull and saves a lot of code if you need it often so my advice is checkout control anchors and the toolbar buttons for positioning before writing code like that again.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Center align on windows forms

  1. Michael T. says:

    thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s