C#通过反射获取当前工程中所有窗体并打开的方法
本文实例讲述了C#通过反射获取当前工程中所有窗体并打开的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Windows.Forms; namespaceTestAppHelperMSDNSample { staticclassProgram { ///<summary> ///Themainentrypointfortheapplication. ///</summary> [STAThread] staticvoidMain() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Formstartup=newForm(); startup.Text="Chooseaformtorun"; startup.Size=newSystem.Drawing.Size(300,300); startup.StartPosition=FormStartPosition.CenterScreen; startup.Load+=newEventHandler(startup_Load); ComboBoxcboForms=newComboBox(); cboForms.Name="cboForms"; cboForms.DropDownStyle=ComboBoxStyle.DropDownList; cboForms.Size=newSystem.Drawing.Size(250,20); cboForms.Location=newSystem.Drawing.Point(25,75); startup.Controls.Add(cboForms); ButtonbtnOpenForm=newButton(); btnOpenForm.Text="OpenForm"; btnOpenForm.Size=newSystem.Drawing.Size(100,30); btnOpenForm.Location=newSystem.Drawing.Point(100,150); btnOpenForm.Click+=newEventHandler(btnOpenForm_Click); startup.Controls.Add(btnOpenForm); Application.Run(startup); } staticvoidbtnOpenForm_Click(objectsender,EventArgse) { ComboBoxcbo=((senderasButton).ParentasForm).Controls["cboForms"]asComboBox; Properties.Settings.Default.LastFormFullName=cbo.SelectedItem.ToString(); Properties.Settings.Default.Save(); Formf=Activator.CreateInstance(Type.GetType(cbo.SelectedItem.ToString()))asForm; f.ShowDialog(); } staticvoidstartup_Load(objectsender,EventArgse) { ComboBoxcbo=((senderasForm).Controls["cboForms"]asComboBox); //loadalltheFormsinexecutingassembly Type[]types=System.Reflection.Assembly.GetExecutingAssembly().GetExportedTypes(); foreach(Typetintypes) { if(t.BaseType==typeof(Form)) { cbo.Items.Add(t.FullName); } } //selectthelastused if(!string.IsNullOrEmpty(Properties.Settings.Default.LastFormFullName)) { if(cbo.Items.Contains(Properties.Settings.Default.LastFormFullName)) { intindex=cbo.FindString(Properties.Settings.Default.LastFormFullName); if(index>=0) cbo.SelectedIndex=index; } } } } }
希望本文所述对大家的C#程序设计有所帮助。