1

Quick question, hopefully an easy fix. I am kinda new to C# and am trying to center a second form, on the secondary screen when it opens. So far I can get it to open on the second screen no problem but it sits in the top left and I cant get it to center. I am aware of the fact that the Location = Screen.AllScreens[1].WorkingArea.Location; will put it in the top left part of said working area. I was wondering if there is a way to (essentially) change the .Location to something else that will center regardless of actual screen size? This will be going onto multiple different systems with varying screen sizes. Here is the code that I have so far.

On the first form.

public partial class FrmPrompt : Form
{
    public FrmPrompt()
    {
        InitializeComponent();
    }

    private void ButNo_Click(object sender, EventArgs e)
    {
        frmConfirm confirm = new frmConfirm();
        Screen[] screens = Screen.AllScreens;
        lblConfirmMsg.Text = "Please Wait For Customer To Confirm...";
        butContinue.Hide();
        confirm.Show();
    }
}

On the second form:

public partial class frmConfirm : Form
{
    public frmConfirm()
    {
        InitializeComponent();
        Location = Screen.AllScreens[1].WorkingArea.Location;
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}

Thanks!

M Reza
  • 18,350
  • 14
  • 66
  • 71
Jambery
  • 13
  • 2
  • 2
    Did [Form.CenterToScreen()](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.centertoscreen.aspx) not do what you wanted? – John Wu May 22 '18 at 03:31
  • if you read what is written there, you will see _Do not call this directly from your code_ remark – vasily.sib May 22 '18 at 04:16

2 Answers2

2

CenterScreen will locate Form on current screen, so if your FrmPrompt on second screen, when you clicking ButNo - this will work. But I think this is not you asking for.

More then that, CenterScreen will overwrite any location setting of your from Location that was setted before Show method invocation. So I suggests to override OnShown method of frmConfirm

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    var area = Screen.AllScreens[1].WorkingArea;
    var location = area.Location;

    location.Offset((area.Width - Width) / 2, (area.Height - Height) / 2);
    Location = location;
}
vasily.sib
  • 3,871
  • 2
  • 23
  • 26
1

try this on the first form, no need to set anything in the 2nd form.

        //put it after this line: frmConfirm confirm = new frmConfirm();
        confirm.StartPosition = FormStartPosition.CenterScreen;
marya
  • 94
  • 6
  • if you set `StartPosition` to `CenterScreen` then form `Location` **will be overwritten** on Show method invocation. – vasily.sib May 22 '18 at 04:15
  • That just centers the 2nd form on the primary display. I need it to center on the secondary display. – Jambery May 22 '18 at 05:40