2010-11-29 44 views
0

爲什麼編譯此創建一個EXE其中:C#編程方式在運行時編譯形式不帶控制檯

  • 打開控制檯
  • 推出的形式?

有什麼可以爲運行時編譯的形式開放單獨沒有控制檯做些什麼呢?

 

//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); 
} 

回答

2

默認情況下,csc編譯控制檯應用程序。您需要將/target:winexe添加到編譯器選項。

1

你試過在命令行參數中加入「target:winexe」嗎?