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

In the picture, the program 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 program's 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;

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 form's position and displays the form.



What did you think of this article?

  • No trackbacks exist for this post.
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.