關於Winform程序窗體間的跳轉問題:
對於編程新手來講,winform程序窗體間的跳轉,經常會出現一些異常,或是彈出重復的窗口,如下圖
下面給出一種方法,可以很好的避免掉這樣的問題:
首先,在主程序Program中,定義一個“找窗體或是創建窗體”的方法,見以下代碼:
1 namespace FormJump 2 { 3 static class Program 4 { 5 public static List<Form> formList = new List<Form>(); 6 /// <summary> 7 /// 找窗體或創建窗體的方法 8 /// </summary> 9 /// <param name="type"></param> 10 /// <returns></returns> 11 internal static Form FindOrCreateFrom(Type type) 12 { 13 Form form = null; 14 foreach (Form formItem in Program.formList) 15 { 16 if (formItem.GetType() == type) 17 { 18 form = formItem; 19 form.Activate(); 20 break; 21 } 22 } 23 if (form == null) 24 { 25 object obj = Activator.CreateInstance(type); 26 if (obj is Form) 27 { 28 form = obj as Form; 29 form.Show(); 30 } 31 } 32 return form; 33 } 34 /// <summary> 35 /// 應用程序的主入口點。 36 /// </summary> 37 [STAThread] 38 static void Main() 39 { 40 Application.EnableVisualStyles(); 41 Application.SetCompatibleTextRenderingDefault(false); 42 Application.Run(new FrmMain()); 43 } 44 } 45 }
然后添加一個FrmChild的子窗體,編寫一個加載和關閉窗體的方法,見以下代碼:
1 namespace FormJump 2 { 3 public partial class FrmChild : Form 4 { 5 public FrmChild() 6 { 7 this.Load += new EventHandler(FrmChild_Load); 8 this.FormClosed += new FormClosedEventHandler(FrmChild_FormClosed); 9 } 10 public void FrmChild_Load(object sender, EventArgs e) 11 { 12 Program.formList.Add(this); 13 } 14 15 public void FrmChild_FormClosed(object sender, FormClosedEventArgs e) 16 { 17 Program.formList.Remove(this); 18 } 19 } 20 }
所有有可能被彈出的窗體都繼承FrmChild窗體
1 public partial class Form1 : FrmChild 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 }
另外,我們在編寫窗體彈出事件的時候,不要再使用一下代碼,
1 /// <summary> 2 /// 打開Form1窗體 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnShow1_Click(object sender, EventArgs e) 7 { 8 Form1 frm1 = new Form1(); 9 frm1.Show(); 10 }
可以直接調用“找窗體或是創建窗體”的方法,所有的窗體彈出都可以調用這樣的方法:
1 /// <summary> 2 /// 打開Form1窗體 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btnShow1_Click(object sender, EventArgs e) 7 { 8 Program.FindOrCreateFrom(typeof(Form1)); 9 } 10 11 private void btnShow2_Click(object sender, EventArgs e) 12 { 13 Program.FindOrCreateFrom(typeof(Form2)); 14 } 15 16 private void btnShow3_Click(object sender, EventArgs e) 17 { 18 Program.FindOrCreateFrom(typeof(Form3)); 19 }
這樣,如若窗體已經打開,可以直接顯示在最前方,如若還沒有彈出,點擊則僅會彈出一個窗體!
關於MDI窗體的跳轉,可以定義一下類似的方法:
private void FindChildForm(Type type) { Form frm = null; foreach (Form frmChild in this.MdiChildren) { if (frmChild.GetType() == type) { frm = frmChild; frm.Activate(); break; } } if (frm==null) { frm = (Form)Activator.CreateInstance(type); frm.MdiParent = this; frm.Show(); } }