Winform程序窗体间的跳转
关于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(); } }
因为相信,所以我去做了......