Position a form so it does not stick off the edge of the screen in C#

[example]

In the picture, the main program (on the bottom) initially positioned the top form so it was hanging off the right and bottom edges of the screen. The program’s code moved the form so it fit in the screen’s lower right corner.

When you click this form’s New Form button, the following code displays a new instance of the form.

// 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.Left + btnShowForm.Width / 2,
        btnShowForm.Top + btnShowForm.Height / 2);

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

    // Create the new form.
    Form1 frm = new Form1();

    // Make sure the form will be completely on the screen.
    Screen screen = Screen.FromControl(this);
    if (screen_pt.X < 0) screen_pt.X = 0;
    if (screen_pt.Y < 0) screen_pt.Y = 0;
    if (screen_pt.X > screen.WorkingArea.Right - frm.Width)
        screen_pt.X = screen.WorkingArea.Right - frm.Width;
    if (screen_pt.Y > screen.WorkingArea.Bottom - frm.Height)
        screen_pt.Y = screen.WorkingArea.Bottom - frm.Height;

    // Position the new form.
    frm.StartPosition = FormStartPosition.Manual;
    frm.Location = screen_pt;
    frm.Show();
}

The code makes a Point representing the center of the button. It calls PointToScreen to translate the point’s coordinates to screen coordinates.

The code then creates a new form. It gets the Screen object that is displaying the form and adjusts the Point‘s coordinates to ensure that the form is completely on that Screen.

Finally, the code sets the new form’s position and displays it.


Download Example   Follow me on Twitter   RSS feed   Donate




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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.