我有一个MainForm,在面板中有一个子表单SubLevel1。在SubLevel1中,我有另一个子表单SubLevel2,它在SubLevel1内的一个面板中打开。现在,在SubLevel2,我将与ShowDialog()一起打开一个ModalForm,我想把它放在SubLevel2 resp之上。MainForm (通过SubLevel1包含SubLevel2 )。
CenterParent只是不能工作,并且无法获得正确的(相对)位置来正确定位ModalForm:
Parent:“无法将顶级控件添加到控件”错误弹出。因此,null. Parent of ModalForm始终是
Owner of ModalForm时,它的位置0,0始终不能用于定位ownerLocation = modalForm.Owner.PointToClient(Point.Empty)时,位置不正确。ownerLocation = modalForm.Owner.PointToScreen(Point.Empty)时,位置不正确。在创建SubForms时,我这样做:
_FormSub = new FormSub() {
TopLevel = false,
TopMost = false
};
panelSub.Controls.Add(_FormSub);
_FormSub.Show();在ModalForm代码中创建SubForm2时,我这样做:
formModal = new formModal() {
Owner = this
};
formModal.ShowDialog();我需要改变什么?
发布于 2022-03-15 12:40:55
通过尝试和错误找到解决方案。
创建ModalForm时,需要将创建的ModalForm的Owner设置为调用表单的TopLevelControl:
FormModal formModal = new FormModal() { Owner = this.TopLevelControl as Form };这也适用于从现有的ModalForm创建另一个ModalForm (然后,现有的ModalForm本身就是TopLevelControl)。
因此,您可以确保所创建的Owner的ModalForm始终具有正确的屏幕位置,通过该可以以编程方式设置ModalForm在其FormLoad()方法中的中心位置:
int centerX = (this.Owner != null) ? this.Owner.Location.X + (this.Owner.Width / 2) : screen.WorkingArea.Width / 2;
int centerY = (this.Owner != null) ? this.Owner.Location.Y + (this.Owner.Height / 2) : screen.WorkingArea.Height / 2;
int locationX = (centerX - (this.Width / 2) > 0) ? centerX - (this.Width / 2) : 0;
int locationY = (centerY - (this.Height / 2) > 0) ? centerY - (this.Height / 2) : 0;
if (locationX > screen.WorkingArea.Width) { locationX = screen.WorkingArea.Width - this.Width; }
if (locationY > screen.WorkingArea.Height) { locationY = screen.WorkingArea.Height - this.Height; }
this.Location = new Point(locationX, locationY);
form.StartPosition = FormStartPosition.Manual;这可以确保在没有使用Parent和CenterParent的情况下打开在调用表单的中央,或者-(如果没有设置Owner )在不使用CenterScreen的情况下以屏幕为中心。
它还确保ModalForm将始终在实际屏幕的边界内打开。
发布于 2022-03-15 12:45:44
我有些东西可以帮你:
private Form Activeform = null;
private void OpenChildForm(Form childForm)
{
if (Activeform != null)
{
Activeform.Close();
}
Activeform = childForm;
childForm.Visible = false;
childForm.BackColor = Color.FromArgb(32, 30, 45);
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}这样就可以使方法可重用。你会称之为它的例子
OpenChildForm(new Form1());https://stackoverflow.com/questions/71481638
复制相似问题