我在面板中有一個帶有子表單SubLevel1的MainForm 。在SubLevel1我有另一個子表單SubLevel2 ,它在SubLevel1的面板中打開。現在,從SubLevel2我打開一個ModalForm并且我想將它居中于SubLevel2之上。MainForm(其中SubLevel2通過SubLevel1包括在內)。ShowDialog()
CenterParent只是不起作用,并且無法獲得正確的(相對)位置來正確定位ModalForm:
從ModalForm開始,我無法設定SubLevel2:彈出“無法將頂級控制元件添加到控制元件”錯誤。因此,ModalForm總是.
ParentParentnull當我將SubLevel2設定為ModalForm
Owner時,它始終具有不能用于定位ModalForm的位置。0,0當我使用
ownerLocation = modalForm.Owner.PointToClient(Point.Empty)的位置不正確。當我使用
ownerLocation = modalForm.Owner.PointToScreen(Point.Empty)的位置不正確。
創建子表單時,我按如下方式進行:
_FormSub = new FormSub() {
TopLevel = false,
TopMost = false
};
panelSub.Controls.Add(_FormSub);
_FormSub.Show();
在SubForm2的代碼中創建ModalForm時,我執行以下操作:
formModal = new formModal() {
Owner = this
};
formModal.ShowDialog();
我需要改變什么?
uj5u.com熱心網友回復:
通過嘗試和錯誤找到了解決方案。
創建 ModalForm 時,您需要將Owner創建的 ModalForm設定TopLevelControl為呼叫表單的 :
FormModal formModal = new FormModal() { Owner = this.TopLevelControl as Form };
這也適用于從現有的 ModalForm 創建另一個 ModalForm(然后現有的 ModalForm 本身就是TopLevelControl)。
因此,您可以確保Owner創建的 ModalForm 始終具有正確的螢屏位置,您可以通過該位置以編程方式在其FormLoad()方法中設定 ModalForm 的居中位置:
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;
這確保了 ModalForm 或者在呼叫表單上方居中打開而不使用,Parent并且- 或CenterParent-(如果沒有Owner設定)在螢屏上居中而不使用CenterScreen.
還確保了 ModalForm 將始終在實際螢屏的邊界內打開。
uj5u.com熱心網友回復:
我有一些東西可以幫助你:
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://www.uj5u.com/qita/450354.html
