通过字符串反射调用窗体
今天查阅了网上一堆通过字符串反射调用窗体的源码,也写了一个。自认为还不错。
/// <summary> /// 反射打开窗口,如果没有主窗体,则会以模式显示。 /// </summary> /// <param name="formName">窗口名称</param> /// <param name="MDIForm">主窗体</param> private static void CreateForm(string formName, MDIMain MDIForm, string formText, params object[] CreateArgs) { MDIForm.Cursor = Cursors.WaitCursor; try { Type mfromType=null; try { mfromType = Type.GetType(formName,true,false); } catch (Exception ex) { throw new Exception(string.Format("创建窗口类时出错!\n类全名:{0}", formName), ex); } Form NewForm = null; foreach (Form formItem in Application.OpenForms) { if (formItem.GetType() == mfromType) { if (formItem.Text == formText) { NewForm = formItem; break; } } } if (NewForm != null) { if (NewForm.WindowState == FormWindowState.Maximized) NewForm.WindowState = FormWindowState.Normal; NewForm.Activate(); } else { try { NewForm = (Form)Activator.CreateInstance(mfromType, CreateArgs); } catch (Exception ex) { throw new Exception(string.Format("窗口加载时出错。\n类全名:{0}\n错误描述:{1}", formName, ex.Message), ex); } try { NewForm.Text = formText; if (MDIForm == null) { MDIForm.Cursor = Cursors.Default; NewForm.ShowDialog(); } else { NewForm.MdiParent = MDIForm; NewForm.Dock = DockStyle.Fill; NewForm.Show(); MDIForm.Cursor = Cursors.Default; } } catch (Exception ex) { throw new Exception(string.Format("窗口打开时出错\n类全名:{0}\n窗口名:{1}\n错误描述:{2}", formName, NewForm.Name, ex.Message), ex); } } } catch (Exception ex) { MyRecorder.Say(ex); } finally { MDIForm.Cursor = Cursors.Default; } }