原文链接
要做一个能动态生成一个简单windowsForm的程序,用CSharpCodeProvider动态编译。
现在倒是可以生成exe了,不过生成的文件打开会有2个窗口,截图如下:
![[C#]关于WindowsForm CSharpCodeProvider动态编译的问题 - 图1](/uploads/projects/yunaoya@ctc727/07293bad35c3ebc51bfba448dce0102a.png)
下面是动态编译部分的代码:
private void menu_export_Click(object sender, EventArgs e){string sourceName = "MyForm.cs";FileInfo sourceFile = new FileInfo(sourceName);CSharpCodeProvider provider = new CSharpCodeProvider();status_content_label.Text = "Exporting ... ";String exeName = String.Format(@"{0}\{1}.exe", "Output/", sourceFile.Name.Replace(".", "_"));CompilerParameters cp = new CompilerParameters();cp.ReferencedAssemblies.Add("System.dll");cp.ReferencedAssemblies.Add("System.Drawing.dll");cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");//cp.ReferencedAssemblies.Add("AxInterop.ShockwaveFlashObjects.dll");//cp.ReferencedAssemblies.Add("Interop.ShockwaveFlashObjects.dll");//cp.ReferencedAssemblies.Add("System.Data.dll");// Generate an executable instead of// a class library.cp.GenerateExecutable = true;// Specify the assembly file name to generate.cp.OutputAssembly = exeName;// Save the assembly as a physical file.cp.GenerateInMemory = false;cp.IncludeDebugInformation = false;// Set whether to treat all warnings as errors.cp.TreatWarningsAsErrors = false;cp.CompilerOptions = "/optimize /win32icon:" + config.GetIconPath() + " MyForm.cs";// Invoke compilation of the source file.CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);string errorMessage;if (cr.Errors.Count > 0){// Display compilation errors.errorMessage = "Errors building {0} into {1}" + sourceName + cr.PathToAssembly + "\n";foreach (CompilerError ce in cr.Errors){errorMessage += " {0}" + ce.ToString() + "\n";}errorReport.ShowError(errorMessage);errorReport.Show();status_content_label.Text = "Failed to create the exe file.";}else{status_content_label.Text = "Exe file successfully created.";}}
然后是MyForm.cs,就是用来动态编译的cs:
using System;using System.Drawing;using System.Windows.Forms;class MyForm : Form{public MyForm(){this.Text = "Hello World";this.StartPosition = FormStartPosition.CenterScreen;}public static void Main(){Application.Run(new MyForm());}}
有没有人能帮忙看看呢?非常感谢!!
找到答案了:
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回答真快
