【问题标题】:C# programmatically Compile Form at Runtime without consoleC# 以编程方式在运行时编译表单,无需控制台
【发布时间】:2010-11-29 10:25:40
【问题描述】:

为什么编译这个会创建一个 exe:

  • 打开控制台
  • 启动表单?

运行时编译的表单单独打开没有控制台可以做什么?

//LIST OF USING using System; using System.Windows.Forms; using System.CodeDom.Compiler; //CODE TO COMPILE string oSource = @" using System.Windows.Forms; using System; namespace fTest { public static class Program { public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyForm()); } } public class MyForm:Form { public MyForm() { this.Text=""Generated exe""; MessageBox.Show(""Generated exe says H3110 W0r1d""); } } }"; string compiledOutput="Generated.exe"; //COMPILATION WORK String [] referenceAssemblies={"System.dll","System.Drawing.dll","System.Windows.Forms.dll"}; CodeDomProvider _CodeCompiler = CodeDomProvider.CreateProvider("CSharp"); System.CodeDom.Compiler.CompilerParameters _CompilerParameters = new System.CodeDom.Compiler.CompilerParameters(referenceAssemblies,""); _CompilerParameters.OutputAssembly = compiledOutput; _CompilerParameters.GenerateExecutable = true; _CompilerParameters.GenerateInMemory = false; _CompilerParameters.WarningLevel = 3; _CompilerParameters.TreatWarningsAsErrors = true; _CompilerParameters.CompilerOptions = "/optimize /target:winexe";//!! HERE IS THE SOLUTION !! string _Errors = null; try { // Invoke compilation CompilerResults _CompilerResults = null; _CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, oSource); if (_CompilerResults.Errors.Count > 0) { // Return compilation errors _Errors = ""; foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors) { _Errors += "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";\r\n\r\n"; } } }catch (Exception _Exception) { // Error occurred when trying to compile the code _Errors = _Exception.Message; } //AFTER WORK if (_Errors==null) { // lets run the program MessageBox.Show(compiledOutput+" Compiled !"); System.Diagnostics.Process.Start(compiledOutput); }else { MessageBox.Show("Error occurred during compilation : \r\n" + _Errors); }

【问题讨论】:

    标签: c# .net forms runtime compilation


    【解决方案1】:

    默认情况下,csc 编译控制台应用程序。您需要在编译器选项中添加/target:winexe

    【讨论】:

      【解决方案2】:

      您是否尝试过在命令行参数中添加“target:winexe”?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多