【问题标题】:C# loading a form from a fileC# 从文件中加载表单
【发布时间】:2018-06-22 12:50:46
【问题描述】:

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

我的问题是我似乎找不到从文件/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;
    }

【问题讨论】:

  • 当您说Form时,您是指完整的承诺窗口表单吗?如果是这样,我认为不可能从文件中加载它。假设您有一个 form1.cs 文件。您将无法从文件中加载它。一旦构建了应用程序。它将变成一个 .exe 并且所有的 .cs 都被编译。
  • 是的,应该提一下,这绝不是要构建的,它是用来保存可以适应 1 种形式的小项目,而不是为每个小测试或模拟器制作新项目。
  • 啊抱歉,我好像弄错了。您想优雅地加载文件。我认为制作一个从目录中获取文件的异步方法会很好。与表单加载不同,它不会阻塞 ui 线程。在这样做的同时,您可以在获取文件时显示一个小微调器或加载器

标签: c# forms listview


【解决方案1】:

这看起来就是你要找的东西:

var form = Activator.CreateInstance(Type.GetType("WindowsFormsApp1." + fi.Name)) 形式; form.ShowDialog();

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

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2012-10-27
    相关资源
    最近更新 更多