如何防止在控制台中打开我动态生成的exe

时间:2013-07-22 10:47:10

标签: c# winforms dynamic-programming codedom system-codedom-compiler

我在c#4.0工作,我想动态生成一个可执行文件,所以我使用了Code Dome,但是当我执行它时在控制台中打开然后我的表单显示,我想生成winform可执行文件。我怎样才能实现我的目标。代码如下:

string Code = @"
using System;
using System.Windows.Forms;

namespace CSBSS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}

public class Form1 : Form
{
}
}

";

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

string tempFolder = @"..\DynamicOutput";
string Output = System.IO.Path.Combine(tempFolder, @"CSBSS.exe");
if (!System.IO.Directory.Exists(tempFolder))
{
    System.IO.Directory.CreateDirectory(tempFolder);
}
else
{
    if (System.IO.File.Exists(Output)) System.IO.File.Delete(Output);
}

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

parameters.TempFiles = new TempFileCollection(tempFolder, false);
//Make sure we generate an exe.
parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = Output;


CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Code);

string OutputMsg = "";
if (results.Errors.Count > 0)
{
    string msgDescr = "";
    foreach (CompilerError CompErr in results.Errors)
    {
        msgDescr += "Line number " + CompErr.Line +
                    ", Error Number: " + CompErr.ErrorNumber +
                    ", '" + CompErr.ErrorText + ";" +
                    Environment.NewLine + Environment.NewLine;
    }
    OutputMsg = @"Error occured while generating executable file, please check following internal error 
" + msgDescr;
    //return false;
}
else
{
    OutputMsg = "Executable file has been generated successfully.";
}

1 个答案:

答案 0 :(得分:2)

使用Windows application

将输出类型指定为CompilerOptions
parameters.CompilerOptions = "/target:winexe";