Reputation: 355
I am trying to center a form in VB.net. Instead of centering the form, it ends up about halfway between center and 0,0(upper left).
I am using the code
Me.StartPosition = FormStartPosition.CenterScreen
Which is called from the IntializeDisplay Method, which in turn is called from the Form Load method.
I assume I'm setting some propertity along the way that messes up the center calculation, but I'm not sure what it could be.
If anyone has any ideas they would be much appreciated.
Thanks.
Upvotes: 2
Views: 8311
Reputation: 1331
If you're resizing the form, or are using auto-size you need to use a
Me.CenterToScreen()
command at the end of the Load event.
Upvotes: 4
Reputation: 889
Instead of relying on the form initialization to handle its starting location, try calling the method to center the form. This allows you to center the form even after you make changes to the size after it is shown.
Example:
Me.CenterToScreen()
Or
Me.CenterToParent()
Depending on where you are trying to center the form.
Upvotes: 1
Reputation:
add this in the event and it will work:
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.StartPosition = FormStartPosition.CenterScreen
End Sub
Upvotes: 4
Reputation: 44307
I think you're setting the value of StartPosition too late in the flow - by the time Form.Load is called, Loading has already completed and the form has an assigned position.
Set a breakpoint on the line of code quoted in your question, and look at the forms position - it will already be in the location it appears.
To have the effect you want, the value of StartPosition needs to be set before the form starts its' built in location processing. I'd suggest putting the code in the form constructor, after the call to InitializeComponent().
Upvotes: 4
Reputation: 5555
Do you have any form resizing/positioning logic implemented? If so, comment it out and try again.
Try setting the Form.StartPosition
in the designer (which will set it in InitializeComponent()
) instead of in the Load event.
Try resetting the Form.Location
and Form.Size
value. If your form is localized, remove the Form.Location
AND Form.Size
entry in the resource file.
Upvotes: 0