正在创建可动态执行的winforms C#

本文关键字:winforms 执行 动态 创建 | 更新日期: 2023-09-27 18:28:29

我想创建一个应用程序,它将从textBox1中取出文本,编译它,并将其保存为可执行文件。我以前从未尝试过,但我真的很想让它发挥作用这是我在"编译器"应用程序中使用的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Diagnostics;
namespace Compiler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            ICodeCompiler icc = codeProvider.CreateCompiler();
            string Output = "out.exe";
            Button ButtonObject = (Button)sender;
            CompilerParameters parameters = new CompilerParameters();
            string[] references = { "System.dll","System.Windows.Forms.dll","System.Drawing.dll" };
            parameters.EmbeddedResources.AddRange(references);
            parameters.GenerateExecutable = true;
            parameters.OutputAssembly = Output;
            CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);
            if (results.Errors.Count > 0)
            {
                foreach (CompilerError CompErr in results.Errors)
                {
                    MessageBox.Show(CompErr.ToString());
                }
            }
            else
            {
                //Successful Compile
                textBox1.ForeColor = Color.Blue;
                textBox1.Text = "Success!";
            }
        }
    }
}

textbox1文本,意味着我试图编译的源是:

class Program
{
    static void Main(string[] args)
    {
System.Windows.Forms.Form f = new System.Windows.Forms.Form(); 
f.ShowDialog();
    }
}

基本上,我试图动态生成一个可执行文件,它只显示一个Form。我也尝试过,而不是制作和显示一个表单来显示System.Windows.MessageBox.show("测试");

在这两种情况下,我都会得到以下错误:

第5行,错误号:CS0234,'类型或命名空间名称命名空间"System"中不存在"Windows"(是否缺少装配参考?);

第5行,错误号:CS0234,'类型或命名空间名称命名空间"System"中不存在"Windows"(是否缺少装配参考?);

正在创建可动态执行的winforms C#

您正在添加3个文件("System.dll"、"System.Windows.Forms.dll"、"System.Drawing.dll")作为嵌入资源而不是引用。将它们添加到ReferencedAssembly中。