如何设置第二形式的位置取决于第一形式

本文关键字:位置 取决于 何设置 设置 | 更新日期: 2023-09-27 18:03:25

我有Form1和Form2和一个按钮在我的项目。当我点击按钮Form2将显示。设置Form2在form1中心位置的命令是什么?

如何设置第二形式的位置取决于第一形式

设置窗体的StartPosition属性为CenterParent。这样它就会一直弹出在中间

您可以在打开时手动设置位置:

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.StartPosition = FormStartPosition.Manual;
        f2.Load += delegate(object s2, EventArgs e2)
        {
            f2.Location = new Point(this.Bounds.Location.X + this.Bounds.Width / 2 - f2.Width / 2,
                this.Bounds.Location.Y + this.Bounds.Height / 2 - f2.Height / 2);
        };
        f2.Show();
    }

这里的关键是将StartPosition设置为手动

在我的系统上,将StartPosition设置为CenterParent并使用Show(this)并不以"所有者"为中心。也许我的系统坏了……我一直都是这样。

您需要使用第二个表单的实例。参见我的2窗体项目的例子

形式1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form2 form2;
        public Form1()
        {
            InitializeComponent();
            form2 = new Form2(this);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            form2.Show();
            string  results = form2.GetData();
        }
    }
}
​

形式2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1;
        public Form2(Form1 nform1)
        {
            InitializeComponent();
            this.FormClosing +=  new FormClosingEventHandler(Form2_FormClosing);
            form1 = nform1;
            form1.Hide();
        }
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            //stops form from closing
            e.Cancel = true;
            this.Hide();
        }
        public string GetData()
        {
            return "The quick brown fox jumped over the lazy dog";
        }
    }
}
​