??本文討論了C# WinForm開發中關于 表單 的一些問題,如:單檔案與多檔案程式、如何避免同一表單多次打開、多檔案程式子表單顯示問題、跨表單傳值等,下面一一闡述,
目錄
- 1 單檔案與多檔案程式
- 1.1 單檔案程式
- 1.2 多檔案程式
- 2 避免同一表單多次打開
- 2.1 平行表單情況
- 2.2 多檔案表單情況
- 3 多檔案程式子表單顯示
- 3.1 父表單不含容器控制元件
- 3.2 父表單含有容器控制元件
- 4 跨表單傳值
1 單檔案與多檔案程式
1.1 單檔案程式
??什么是 單檔案程式(SDI) ——單個檔案、表單或多個獨立表單組成,且每次只能處理一個當前激活的檔案,如畫圖工具、文本檔案等,如下便是一個單檔案程式:

當然,擁有若干(≥2)獨立表單的程式也是單檔案程式!
1.2 多檔案程式
??什么是 多檔案程式(MDI) ——多個檔案或表單組成(同一公共界面之下),常分為父表單、子表單,多檔案應用程式可同時打開多個子表單,但只能有一個處于激活狀態,如Excel,其實,MDI并未引進什么高級技術——它僅是把具有多個表單的SDI改造成MDI了,下面展示一個多檔案程式:

其代碼如下:
private void frmMain_Load(object sender, EventArgs e)
{
//this.IsMdiContainer = true;//【屬性界面】也可設定
//this.WindowState = FormWindowState.Maximized;
frmChildOne childOne = new frmChildOne();
childOne.MdiParent = this;
childOne.Show();
frmChildTwo childTwo = new frmChildTwo();
childTwo.MdiParent = this;
childTwo.Show();
this.LayoutMdi(MdiLayout.TileHorizontal);//子表單排列方式
}
2 避免同一表單多次打開
2.1 平行表單情況
??打開表單代碼:
private void toolStripOpenWnd_Click(object sender, EventArgs e)
{
if (Application.OpenForms["frmTwo"] == null)
{
frmTwo frm2 = new frmTwo();
frm2.StartPosition = FormStartPosition.CenterScreen;//居中
frm2.Show();
return;
}
Application.OpenForms["frmTwo"].WindowState = FormWindowState.Normal;
}
??運行效果(多次點擊“打開表單”):

2.2 多檔案表單情況
??打開子表單代碼:
private bool IsChildfrmOpen(string childName)
{
foreach(var frm in this.MdiChildren)
{
if (frm.Name == childName)
{
frm.WindowState = FormWindowState.Normal;
return true;
}
}
return false;
}
private void toolStripOpenWnd_Click(object sender, EventArgs e)
{
if (IsChildfrmOpen("frmTwo"))
{
return;
}
frmTwo frm2 = new frmTwo();
frm2.MdiParent = this;
frm2.StartPosition = FormStartPosition.CenterScreen;//居中
frm2.Show();
}
??運行效果(多次點擊“打開表單”):

3 多檔案程式子表單顯示
3.1 父表單不含容器控制元件
??界面設計:

??顯示子表單代碼:
private void toolStripOpenWnd_Click(object sender, EventArgs e)
{
if (IsChildfrmOpen("frmTwo"))
{
return;
}
frmTwo frm2 = new frmTwo();
frm2.MdiParent = this;
frm2.StartPosition = FormStartPosition.CenterScreen;//居中
frm2.Show();
}
3.2 父表單含有容器控制元件
??界面設計:

當使用3.1節代碼時, MDI子表單被容器控制元件遮擋:

??正確的顯示子表單代碼:
using System.Runtime.InteropServices;
/*----------------------------------------*/
/*-------------------以下置于類里面-------------------*/
[DllImport("user32")] //類里面
public static extern int SetParent(int hWndChild, int hWndNewParent);
private void toolStripOpenWnd_Click(object sender, EventArgs e)
{
if (IsChildfrmOpen("frmTwo"))
{
return;
}
frmTwo frm2 = new frmTwo();
frm2.MdiParent = this;
frm2.StartPosition = FormStartPosition.CenterScreen;//居中
frm2.Show();
SetParent((int)frm2.Handle, (int)this.Handle);
}
/*---------------------------------------------------------*/
運行效果:

4 跨表單傳值
??跨表單傳值一般使用:
- 表單級靜態欄位;
- 表單Tag屬性;
- App.config組態檔;
- 委托事件方法、公有屬性方法;
- ……
可參考:C#兩種子父表單傳值方法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266331.html
標籤:其他
上一篇:JAVA集合詳解(一)
