Reputation: 1786
From msdn:
Do not call this directly from your code. Instead, set the StartPosition property to CenterScreen.
Anyone know why?
Upvotes: 2
Views: 1002
Reputation: 941495
For the usual reason when you see this annotation in the MSDN Library, there are way too many odds that you'll use this wrong. There is only one place in code where you can call this method and get the expected result.
This is trouble caused by the form's Size property. Required to know how to center it of course. Too many programmers take the value of it they see in the Properties window as gospel, they'll assume that the window will have that size on the user's machine as well. This is very rarely the case.
The first problem are the user preferences, they can change the size of the caption text and the control buttons. Or they'll have Aero enabled (or not) which gives the window fat borders. This can cause the Size to be off by a subtle amount, the actual window's Size will be different at runtime from what you see in your Properties window. Something that's already accommodated by Winforms, it doesn't actually store the Size property of your design, it stores the ClientSize property. Actual Size is not known until the window is created, when the CreateHandle() method runs. So you cannot call CenterToScreen() in the form's constructor nor can you call it before the Show() call, that's too early.
The second problem is the form's AutoScaleMode property. Especially important lately, many users no longer run their machine at the default setting of 96 DPI. Made especially easy to change since Vista. This will cause the window's Size to be off much more dramatically. Actual Size is not known until the window is rescaled, completed when the OnLoad() method runs.
Calling it later produces visual artifacts, the user can actually see the window move on the screen. So there's just one place, the form's OnLoad() method/Load event handler. But it already happens there, that's where the StartPosition property is applied when it is set to CenterScreen. So there's no remaining reason to ever call it yourself. It should have been a private method, hard to fix such design mistakes later of course.
Upvotes: 9