Pages

Ads 468x60px

Thursday, August 16, 2012

Center A Form to another form in C#

Recently, while I was using C#, I had an issue. I wanted to center a form in the middle of another form. After drawing a chart and doing some math, I have come up with this piece of code:

form2.SetDesktopLocation(form1.Location.X + ((form1.Width / 2) - form2.Width / 2), form1.Location.Y + ((form1.Height / 2) - form2.Height / 2));
What this code actually does, is it first gets the location of form1 X. It then adds that to form1 Width / 2, and subtracts that from form2's width / 2, and does the same for Y. It does that, because you get the X position, and that position needs to be in the center of form1's width. Then, you need to factor in half of form2's width per side, because form1's width was divided by 2. Don't worry if you do not understand. This code assumes the form you want to center is form2, and the form you want to center it around is form1. You have to create a variable for the current instance of form1 and form2. Here is an example of that:

Form1 form1 = (Form1)Application.OpenForms[0];
What this code does, is it gets a current array of the open forms. If form2 is your child form, and form 1 is your main form, form1 would be position [0] and form2 would be position [1].

Here is a picture of this:



I hope it helps!

1 comments:

  1. Playtech - Dr.MD
    Playtech is a well-known and 통영 출장안마 trusted casino software 당진 출장샵 developer. Today, it is recognized as one of the leading casino software companies in the world, 파주 출장샵 with 🎁 Bonus: 100% up 양산 출장샵 to C$250💻 Software provider: Playtech 속초 출장마사지

    ReplyDelete