fedeteka fedeteka - 2 months ago 12
Vb.net Question

Center a TabControl on a Form and a Panel on the TabControl

A WindowsForm application with this setting on the Design view:

MainForm.WindowState = Maximized

TabControl.Dock = None

ControlPanel(Inside the TabControl).Dock = None

I need to center the TabControl on the Form and the Panel on the TabControl

Using

TabControl.Top = (Me.ClientSize.Height / 2)
TabControl.Left = (Me.ClientSize.Width / 2)


The TabControl it's shown far to the left and far below.

Almost the same result using Me.DisplayRectangle.Height / 2 and Me.DisplayRectangle.Width

Also tried with

TabControl.Anchor = AnchorStyles.None


as suggested on some sites but didn't work

Using

TabControl.Top = (Me.ClientSize.Height / 4)
TabControl.Left = (Me.ClientSize.Width / 4)


The TabControl looks more centered...

What can be wrong? A setting on Design time?

Answer

The red shows the height and width of the form, and the blue shows half of those dimensions. So using 1/2 doesn't make sense.

enter image description here

The correct math would involve the size of the tabcontrol

TabControl1.Top = (Me.ClientSize.Height - TabControl1.Height) \ 2
TabControl1.Left = (Me.ClientSize.Width - TabControl1.Width) \ 2

enter image description here

You could put it in the form's resize event and load

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    centerTabControlInForm()
End Sub

Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
    centerTabControlInForm()
End Sub

Private Sub centerTabControlInForm()
    TabControl1.Top = (Me.ClientSize.Height - TabControl1.Height) \ 2
    TabControl1.Left = (Me.ClientSize.Width - TabControl1.Width) \ 2
End Sub

Similarly, you can do something like this with the panel relative to the tab control. You may also want to resize the controls as the form resizes, but that is outside the scope of your question...