Click here to Skip to main content
15,884,425 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys,

I have a question regarding vb.net form positioning. i have two forms, form1 and form2. i have a button in form1 to show form 2. but when i move form1 and click the button form2 show not in the center. I want form2 always show in the center of form1 even it from another location. thanks
Posted

If you do not mind the form being shown modal, then this would work:
VB
Dim f2 As New Form2
f2.StartPosition = FormStartPosition.CenterParent
f2.ShowDialog()

Else:
VB
Dim f2 As New Form2
f2.StartPosition = FormStartPosition.Manual
f2.Location = New Point(Me.Location.X + Me.Width \ 2 - f2.Width \ 2, Me.Location.Y + Me.Height \ 2 - f2.Height \ 2)
f2.Show()

Where "Me" is the form that shows "f2".
 
Share this answer
 
Comments
Johnny J. 20-May-13 4:15am    
There is no difference between Show() and ShowDialog() apart from the modal aspect, so StatupPosition = CenterParent will work even for non-modal forms.

You do, however, need to supply a parent (which you don't) and call f2.ShowDialog(Me) or f2.Show(Me).

You really shouldn't use manual startup position and manual position calculation for this, that's the way it was done 20 years ago...
 
Share this answer
 
Set Form2's StartupPosition property to CenterOwner

When you open the form from Form1 using Show or ShowDialog, add the ownerform as parameter to the method call:

Dim frm2 As New Form2
frm2.ShowDialog(Me)

Where Me is the form you're calling it from, i.e. Form1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900