Share via

Form stucked inside a panel

rahul kumar 605 Reputation points
2023-06-25T07:29:51.9233333+00:00

Hi , i am trying to place a Form (which is added to a panel at run time) to the centre of the panel but found that it is always being positioned to the top left side of the Panel . Below is the code

// mainmaster is the Form name,login is another form .panel1 is placed inside the mainmaster .

  private void mainmaster_Load(object sender, EventArgs e)
        {
            login hm = new login();
            hm.TopLevel = false;
            hm.FormBorderStyle = FormBorderStyle.None;
            hm.StartPosition = FormStartPosition.CenterParent;
            hm.ControlBox = false;           
            panel1.Controls.Add(hm);
            hm.BringToFront();
            hm.Show();

        }


i have also tried to set the startposition property to centerparent in the designer toolbox window of login.cs but no avail . Please suggest what should i do Centre it .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Anonymous
2023-06-26T03:14:48.5666667+00:00

Hi @Rahul Kumar , Welcome to Microsoft Q&A.

You need to set the location manually.

You also need to set the anchor attribute.

private void Form1_Load(object sender, EventArgs e)
{
    Form2 hm = new Form2();
    hm.TopLevel = false;
    hm.FormBorderStyle = FormBorderStyle.None;
    hm.StartPosition = FormStartPosition.Manual; // Set the start position to Manual
    hm.Location = new Point((panel1.Width - hm.Width) / 2, (panel1.Height - hm.Height) / 2); // Calculate the center position
    hm.Anchor = AnchorStyles.None; // Set the Anchor property to None
    panel1.Controls.Add(hm);
    hm.BringToFront();
    hm.Show();
}

User's image

Best Regards,

Jiale


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.