Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to centre one form on another?

Status
Not open for further replies.

GlynA

Programmer
May 1, 2002
77
0
0
GB
I have a form Form1 which needs to show Form2 centred on itself.
This is achieved in VB6 by setting the StartupPosition property of Form2 to CentreOwner. Form1 simply then uses Form2.show vbModal.
How can I achieve the same result in VB.NET?

 
Set the StartPosition property of Form2 to CenterParent


Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
 
Thanks for the suggestion. It seems to work in a simple application, but for some reason it does not work in the application I am working on. Form2 appears in various positions near the top left of the screen!

Investigating a little, it appears that if Form1 is an MDI child then Form2 is centred on the MDI parent rather than on Form1.

Any more ideas anyone?

Thanks in advance.

Glyn.
 
My problem appears to be due to the fact that Form2 contains an Activex control. The initialisation of this control stops the CentreParent property functioning correctly.
Has anyone else come across this problem or have any ideas for a workaround?

Glyn.
 
Only way I have seen to do this as of yet is to pass the form that you will use to center on. As in pass the parent form to the child. The best way to do this is overload the MyBase.New
This is what you want.

In your child add this.

Private ParentForm as "frmParentName"

Inside the windows forms designer code overload the Sub New like this.

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

Public Sub New(ByRef tmpForm As "frmParentForm")

MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call
ParentForm = tmpForm
End Sub


This will overload the Sub New command so when you goto call the form in your parent form you will now call it like this.

ChildForm = New frmChildForm(Me)

Now inside your child form on the load you can center it to the parent like this.

Public Sub CenterMe(ByRef tmpForm As Form, ByRef _ tmpParentForm As frmParentForm)

tmpForm.Left = (tmpParentForm.Left.ToString + ((tmpParentForm.Width.ToString / 2) - (tmpForm.Width / 2)))
tmpForm.Top = (tmpParentForm.Top.ToString + ((tmpParentForm.Height.ToString / 3) - (tmpForm.Height / 2)))

I know this is alot of code but if you put it in a module you can center all your forms on any parent or passed form.
Hope it helps you out.

-Matt

End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top