Mark Kramer
Mark Kramer

Reputation: 3214

How to get an object to center in a form

I'm trying to simply center a panel in a form. I do this by using the simple formula of Object Location = (Container Width - Object Width) / 2. That's a simple mathematical way of moving an object to the center of its container (x-axis).

However, it isn't working properly. It's putting probably about 10 pixels of extra space on the left side and I can't figure out why. If you reduce the size of the form enough, the panel touches the right side of the form, but is still about ten pixels away from the left side.

I've checked to make sure that any margin or padding properties are set to 0, but with no luck.

Does anybody know why this is happening and how to fix it?

Here is my exact code:

Private Sub Form_Loaded(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'Center Object
    pnlRadios.Location = New Point((Me.Width - pnlRadios.Width) / 2, 5)
End Sub

Update: I also tried:

pnlRadios.Location = New Point(Me.Width / 2 - pnlRadios.Width /2 , 5)

and

pnlRadios.Left = Me.Width / 2 - pnlRadios.Width / 2

and got the exact same results with every attempt.

Update 2: I was able to do a manual workaround by adding - 10 to the formula. It's centered now but it feels like I cheated and I still don't know why I had to do that in the first place, I can't figure out why there's some sort of padding on the left side.

Upvotes: 1

Views: 5815

Answers (1)

Louis van Tonder
Louis van Tonder

Reputation: 3700

Have you tried this? I beleive I had the same issue a few years ago. I think it had todo with this:

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.desktopbounds(v=vs.110).aspx

The display width, can be different from the actual width of the form... in pixels.. (maybe theming.. who knows...)

Run this code...

MsgBox("width = " & Me.Width & vbCrLf & vbCrLf & _ 
"desktopbound width = " &  Me.DisplayRectangle.Width)

Edit: As per the OP's clarification in the comments below, to get the actual "middle" of the form, without borders and decoration:

"

I don't want to include the borders in this which explains why I was having this problem. This works:

pnlRadios.Location = New Point((Me.DisplayRectangle.Width - pnlRadios.Width) / 2, 5)

"

Upvotes: 1

Related Questions