Cool site to make money from PTC ,PTU and PTS sites and adfly,,youtube,facebool,twitter,neobux,probux and blogging tips, tools, tutorials many things.

Center A Form to another form in C#

by OTHMAN OMER OTHMAN ALAMODI , at 6:24 PM , have 0 comments
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!
Center A Form to another form in C# - written by OTHMAN OMER OTHMAN ALAMODI , published at 6:24 PM, categorized as .Net , C# . And have 0 comments
No comment Add a comment
Cancel Reply
Theme designed by Damzaky - Published by Proyek-Template
Powered by Blogger