二级屏幕上的中心C#表格

时间:2018-05-22 03:25:19

标签: c# forms location center screens

快速提问,希望很容易解决。 我是C#的新手,我试图在第二个窗体中打开第二个窗体。到目前为止,我可以让它在第二个屏幕上打开没问题,但它位于左上方,我不能让它到中心。我知道Location = Screen.AllScreens[1].WorkingArea.Location;会把它放在所述工作区的左上角。我想知道是否有办法(基本上)将.Location更改为其中一个无论实际屏幕尺寸如何都会居中的东西?这将进入具有不同屏幕尺寸的多个不同系统。 这是我到目前为止的代码。

在第一张表格上。

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();
    }
}

在第二种形式上:

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

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

谢谢!

2 个答案:

答案 0 :(得分:1)

在第一个表单上尝试这个,不需要在第二个表单中设置任何内容。

        //put it after this line: frmConfirm confirm = new frmConfirm();
        confirm.StartPosition = FormStartPosition.CenterScreen;

答案 1 :(得分:1)

CenterScreen会在当前屏幕上找到表单,因此,如果您在第二个屏幕上FrmPrompt,当您点击ButNo时 - 这将有效。但我认为这不是你要求的。

然后,CenterScreen 将覆盖在显示方法调用之前设置的位置的任何位置设置。所以我建议覆盖frmConfirm

的OnShown方法
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;
}