Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a Windows form on a secondary monitor?

I'm trying to set a Windows Form on secondary monitor, as follows:

private void button1_Click(object sender, EventArgs e)
{
    MatrixView n = new MatrixView();
    Screen[] screens = Screen.AllScreens;
    setFormLocation(n, screens[1]);
    n.Show();
}

private void setFormLocation(Form form, Screen screen)
{
    // first method
    Rectangle bounds = screen.Bounds;
    form.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height);

    // second method
    //Point location = screen.Bounds.Location;
    //Size size = screen.Bounds.Size;

    //form.Left = location.X;
    //form.Top = location.Y;
    //form.Width = size.Width;
    //form.Height = size.Height;
}

The properties of bounds seem correct, but in both methods I've tried, this maximizes the form on the primary monitor. Any ideas?

like image 781
David Hodgson Avatar asked Sep 01 '09 16:09

David Hodgson


3 Answers

this.Location = Screen.AllScreens[1].WorkingArea.Location;

this is the Form reference.

like image 156
Gengi Avatar answered Oct 07 '22 22:10

Gengi


Try setting StartPosition parameter as FormStartPosition.Manual inside your SetFormLocation method.

like image 41
Sesh Avatar answered Oct 07 '22 22:10

Sesh


@Gengi's answer is succinct and works well. If the window is maximised it does not move the window. This snippet solves that (although I suspect the windows "normal" dimensions must be smaller than the new screen dimensions for this to work):

    void showOnScreen(int screenNumber)
    {
        Screen[] screens = Screen.AllScreens;

        if (screenNumber >= 0 && screenNumber < screens.Length)
        {
            bool maximised = false;
            if (WindowState == FormWindowState.Maximized)
            {
                WindowState = FormWindowState.Normal;
                maximised = true;
            }
            Location = screens[screenNumber].WorkingArea.Location;
            if (maximised)
            {
                WindowState = FormWindowState.Maximized;
            }
        }
    }
like image 12
Alex Strickland Avatar answered Oct 07 '22 22:10

Alex Strickland