欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-30 10:20:04
本文实例讲述了c#通过反射获取当前工程中所有窗体并打开的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.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#程序设计有所帮助。