C#从文件加载表单

时间:2018-06-22 03:36:13

标签: c# forms listview

我正在制作一个程序,通过单击列表视图中的名称,可以打开项目文件夹中的任何表单。

我的问题是我似乎找不到从文件/ FileInfo对象加载/创建表单的方法

我想知道是否有更好的方法将表单加载到列表中,这样可以更轻松地加载表单?

PS:重点是事先不知道表单名称,或者必须执行任何代码才能打开表单。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
public partial class FolderList : Form {
    FolderReader fr;
    List<FileInfo> fileList;


    public FolderList() {
        InitializeComponent();
        fr = new FolderReader();
    }

    private void Form1_Load(object sender, EventArgs e) {

        this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
        this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        this.AutoSize = true;
        this.AutoSizeMode = AutoSizeMode.GrowAndShrink;

        fileList = fr.Read();

        foreach (FileInfo file in fileList) {
            ListViewItem item = new ListViewItem(file.Name);
            item.Tag = file;
            LVApps.Items.Add(item);
        }


    }

    private void HandleDoubleClick(object sender, MouseEventArgs e) {
        ListViewItem selected = LVApps.SelectedItems[0];
        FileInfo fi = (FileInfo)selected.Tag;

        //Here i would like to open a form from the file given above

        Debug.WriteLine(fi.Name);
    }
  }
} 

文件夹阅读器:

public List<FileInfo> Read() {

        String dir = Directory.GetCurrentDirectory();
        dir = dir.Substring(0, dir.Length - 9);
        dir = dir + "Forms";

        Debug.WriteLine(dir);

        List<FileInfo> fileList = new List<FileInfo>();
        DirectoryInfo di = new DirectoryInfo(dir);
        FileInfo[] files = di.GetFiles("*.cs");
        foreach (FileInfo file in files) {
            if (!file.FullName.Contains("Design")) {
                fileList.Add(file);
            }

            return fileList;

        }
        return null;
    }

1 个答案:

答案 0 :(得分:2)

这似乎是您要寻找的东西:

  

var form = Activator.CreateInstance(Type.GetType(“ WindowsFormsApp1。” +   fi.Name))为表格; form.ShowDialog();

来自:https://stackoverflow.com/a/37523007/7911333