首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → C#通过反射获得当前工程中所有窗体并打开实现例子

C#通过反射获得当前工程中所有窗体并打开实现例子

来源:维维整理 发布时间:2015-8-21 7:58:54 人气:

C#如何通过反射获得当前工程中所有窗体并打开实现例子,本文讲述了C#通过反射获取当前工程中所有窗体并打开的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestAppHelperMSDNSample
{
 static class Program
 {
  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Form startup = new Form();
   startup.Text = "Choose a form to run";
   startup.Size = new System.Drawing.Size(300, 300);
   startup.StartPosition = FormStartPosition.CenterScreen;
   startup.Load += new EventHandler(startup_Load);
   ComboBox cboForms = new ComboBox();
   cboForms.Name = "cboForms";
   cboForms.DropDownStyle = ComboBoxStyle.DropDownList;
   cboForms.Size = new System.Drawing.Size(250, 20);
   cboForms.Location = new System.Drawing.Point(25, 75);
   startup.Controls.Add(cboForms);
   Button btnOpenForm = new Button();
   btnOpenForm.Text = "Open Form";
   btnOpenForm.Size = new System.Drawing.Size(100, 30);
   btnOpenForm.Location = new System.Drawing.Point(100, 150);
   btnOpenForm.Click += new EventHandler(btnOpenForm_Click);
   startup.Controls.Add(btnOpenForm);
   Application.Run(startup);
  }
  static void btnOpenForm_Click(object sender, EventArgs e)
  {
   ComboBox cbo = ((sender as Button).Parent as Form).Controls["cboForms"] as ComboBox;
   Properties.Settings.Default.LastFormFullName = cbo.SelectedItem.ToString();
   Properties.Settings.Default.Save();
   Form f = Activator.CreateInstance(Type.GetType(cbo.SelectedItem.ToString())) as Form;
   f.ShowDialog();
  }
  static void startup_Load(object sender, EventArgs e)
  {
   ComboBox cbo = ((sender as Form).Controls["cboForms"] as ComboBox);
   // load all the Forms in executing assembly
   Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetExportedTypes();
   foreach (Type t in types)
   {
    if (t.BaseType == typeof(Form))
    {
     cbo.Items.Add(t.FullName);
    }
   }
   // select the last used
   if (!string.IsNullOrEmpty(Properties.Settings.Default.LastFormFullName))
   {
    if(cbo.Items.Contains(Properties.Settings.Default.LastFormFullName))
    {
     int index = cbo.FindString(Properties.Settings.Default.LastFormFullName);
     if (index >= 0)
      cbo.SelectedIndex = index;
    }
   }
  }
 }
}
相关下载
栏目导航
本类热门阅览