Bug With CenterParent

One may think that centering a window is an easy task. Just set StartPosition to CenterParent and everything should work. This is true in most cases, however there is one bug that makes things more annoying than it should be.

Reproducing bug

First step should always be to reproduce buggy behaviour. In this case it is fairly easy. Just make new application with two forms. One parent we will at default settings and one child for which we will change StartPosition to CenterParent. On main form create two buttons. First button should show modal window (ShowDialog) and second should create just owned window (Show) like in this example.

When you click on second button you will notice that form isn't centered at all. Every window created just goes to next default position.

Although this is definitely a bug, Microsoft decided not to fix it. Explanation is rather strange: "a fix here would be a breaking change to the behavior of WinForms 1, 1.1 and 2.". I am not challenging that it would be a change to fix it but how many people would it really affect in negative manner. I personally cannot imagine one person setting child form to CenterParent and then being angry because form is centered.

Workaround

Like in "good old days" we need to center it manually. Do not forget to set StartPosition to manual and then just use some good old mathematics to fix it.

Resolution

Real solution would be to fix it in framework but since it is already rejected, I wouldn't hold my breath for it. Easier solution (.NET Framework 3.5) would be to create extension method and solve it there. It is not resolution as such but it makes whole look nice when you need it.

Leave a Reply

Your email address will not be published. Required fields are marked *