Central form on screen or on parent

Since the built-in functionality for positioning forms in VB.NET is not always suitable for use, I am trying to make my sub for this.

But I missed something ...

Public Sub form_center(ByVal frm As Form, Optional ByVal parent As Form = Nothing) Dim x As Integer Dim y As Integer Dim r As Rectangle If Not parent Is Nothing Then r = parent.ClientRectangle x = r.Width - frm.Width + parent.Left y = r.Height - frm.Height + parent.Top Else r = Screen.PrimaryScreen.WorkingArea x = r.Width - frm.Width y = r.Height - frm.Height End If x = CInt(x / 2) y = CInt(y / 2) frm.StartPosition = FormStartPosition.Manual frm.Location = New Point(x, y) End Sub 

How to get this sub-place the correct form form in the middle of the screen or another form, if defined?

+7
source share
4 answers

The code is simply incorrect. It is also very important that this code works late enough, the constructor is too early. Do not forget to call it from the "Download" event, then the form will automatically scale correctly and configure for user settings, the StartPosition property no longer matters. To fix:

 Public Shared Sub CenterForm(ByVal frm As Form, Optional ByVal parent As Form = Nothing) '' Note: call this from frm Load event! Dim r As Rectangle If parent IsNot Nothing Then r = parent.RectangleToScreen(parent.ClientRectangle) Else r = Screen.FromPoint(frm.Location).WorkingArea End If Dim x = r.Left + (r.Width - frm.Width) \ 2 Dim y = r.Top + (r.Height - frm.Height) \ 2 frm.Location = New Point(x, y) End Sub 

By the way, one of the few reasons that actually implements the Load event handler.

+15
source share

I know this is an old post, and this does not answer the question directly, but for anyone who stumbles upon this topic, centering the form can be done simply without the need to write your own procedure.

System.Windows.Forms.Form.CenterToScreen() and System.Windows.Forms.Form.CenterToParent() allow you to center the form using a link to the screen or a link to the parent form, depending on which one you need,

It should be noted that these procedures MUST be called before the form is loaded. It is best to call them in the form_load event handler.

EXAMPLE CODE:

  Private Sub Settings_Load(sender As Object, e As EventArgs) Handles Me.Load Me.CenterToScreen() 'or you can use Me.CenterToParent() End Sub 
+21
source share

This may also be useful:

  myForm.StartPosition = FormStartPosition.CenterParent myForm.ShowDialog() 

You can also use FormStartPosition.CenterScreen

+4
source share

I had a problem with StartPosition = CenterParent which is not working. I decided to use the .ShowDialog() form instead of .Show() :

 ' first you should set your form Start Position as Center Parent Private Sub button_Click(sender As Object, e As EventArgs) Handles button.Click MyForm.ShowDialog() End Sub 
0
source share

All Articles