原文链接
    要做一个能动态生成一个简单windowsForm的程序,用CSharpCodeProvider动态编译。
    现在倒是可以生成exe了,不过生成的文件打开会有2个窗口,截图如下:

    [C#]关于WindowsForm CSharpCodeProvider动态编译的问题 - 图1

    下面是动态编译部分的代码:

    1. private void menu_export_Click(object sender, EventArgs e)
    2. {
    3. string sourceName = "MyForm.cs";
    4. FileInfo sourceFile = new FileInfo(sourceName);
    5. CSharpCodeProvider provider = new CSharpCodeProvider();
    6. status_content_label.Text = "Exporting ... ";
    7. String exeName = String.Format(@"{0}\{1}.exe", "Output/", sourceFile.Name.Replace(".", "_"));
    8. CompilerParameters cp = new CompilerParameters();
    9. cp.ReferencedAssemblies.Add("System.dll");
    10. cp.ReferencedAssemblies.Add("System.Drawing.dll");
    11. cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
    12. //cp.ReferencedAssemblies.Add("AxInterop.ShockwaveFlashObjects.dll");
    13. //cp.ReferencedAssemblies.Add("Interop.ShockwaveFlashObjects.dll");
    14. //cp.ReferencedAssemblies.Add("System.Data.dll");
    15. // Generate an executable instead of
    16. // a class library.
    17. cp.GenerateExecutable = true;
    18. // Specify the assembly file name to generate.
    19. cp.OutputAssembly = exeName;
    20. // Save the assembly as a physical file.
    21. cp.GenerateInMemory = false;
    22. cp.IncludeDebugInformation = false;
    23. // Set whether to treat all warnings as errors.
    24. cp.TreatWarningsAsErrors = false;
    25. cp.CompilerOptions = "/optimize /win32icon:" + config.GetIconPath() + " MyForm.cs";
    26. // Invoke compilation of the source file.
    27. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
    28. string errorMessage;
    29. if (cr.Errors.Count > 0)
    30. {
    31. // Display compilation errors.
    32. errorMessage = "Errors building {0} into {1}" + sourceName + cr.PathToAssembly + "\n";
    33. foreach (CompilerError ce in cr.Errors)
    34. {
    35. errorMessage += " {0}" + ce.ToString() + "\n";
    36. }
    37. errorReport.ShowError(errorMessage);
    38. errorReport.Show();
    39. status_content_label.Text = "Failed to create the exe file.";
    40. }
    41. else
    42. {
    43. status_content_label.Text = "Exe file successfully created.";
    44. }
    45. }

    然后是MyForm.cs,就是用来动态编译的cs:

    1. using System;
    2. using System.Drawing;
    3. using System.Windows.Forms;
    4. class MyForm : Form
    5. {
    6. public MyForm()
    7. {
    8. this.Text = "Hello World";
    9. this.StartPosition = FormStartPosition.CenterScreen;
    10. }
    11. public static void Main()
    12. {
    13. Application.Run(new MyForm());
    14. }
    15. }

    有没有人能帮忙看看呢?非常感谢!!

    找到答案了:
    cp.CompilerOptions = “/target:winexe /optimize /win32icon:” + config.GetIconPath() + “ MyForm.cs”;
    在 cp.CompilerOptions 中 加一句 /target:winexe 就可以了 默认是 Console app
    http://stackoverflow.com/questions/7497493/problems-using-windowsform-and-csharpcodeprovider
    话说stackoverflow回答真快