Position a form over another form in C#


When you click this example’s button, the program uses the following code to display a new instance of the main form positioned next to the button’s lower left corner (as shown in the picture).

// Position a new instance of this form
// just to the right and below the button.
private void btnShowForm_Click(object sender, EventArgs e)
    // Get the location in this form's coordinate system.
    Point form_pt = new Point(btnShowForm.Right, btnShowForm.Bottom);

    // Translate into the screen coordinate system.
    Point screen_pt = this.PointToScreen(form_pt);

    // Create and position the form.
    Form1 frm = new Form1();
    frm.StartPosition = FormStartPosition.Manual;
    frm.Location = screen_pt;

The code creates a Point that holds the new form’s desired location in this form’s coordinate system. It then calls the form’s PointToScreen method to convert the point into screen coordinates.

The code finishes by creating, positioning, and displaying a new form. The only real trick here is remembering to set the new form’s StartPosition property to Manual so the form is positioned where its Location property says it should be instead of at a default position.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in forms, user interface and tagged , , , , , , , , , . Bookmark the permalink.