欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

C#通过反射获取当前工程中所有窗体并打开的方法

来源:本站原创|时间:2020-01-10|栏目: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;
    }
   }
  }
 }
}

希望本文所述对大家的C#程序设计有所帮助。

上一篇:关于ASP网页无法打开的解决方案

栏    目:C#教程

下一篇:没有了

本文标题:C#通过反射获取当前工程中所有窗体并打开的方法

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/7055.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有