2017-01-09 41 views
0

動態生成.exe文件我有一個按鈕「cmdGenerate」的應用程序。我想要的是,當我點擊該按鈕時,它需要創建一個控制檯應用程序,並在其中包含特定的代碼。使用VB.NET

例如是需要生成控制檯應用程序具有這樣的功能:

Dim WIDTH as integer = someValuePlacedWhenGeneratingFile 
    Dim HEIGHT as integer = someValuePlacedWhenGeneratingFile 

    Function calculateArea(x as Integer, y as Integer) as Integer 
     return x*y 
    End Function 

someValuePlacedWhenGeneratingFile就是我想要生成文件時改變。那可能嗎 ?

生成的exe文件應該只是像一個在上面,WIDTH和HEIGHT集,而我會在我的主發電機的應用設定值的功能的控制檯應用程序。

+2

的可能的複製[?動態創建從源代碼編譯的.NET EXE](http://stackoverflow.com/questions/3591587/動態創建編譯網絡exe源代碼) – GSerg

+1

使用@GSerg提到的副本;只需將「CSharp」替換爲「VisualBasic」(對於一個答案)或將「Csc」替換爲「vbc」替換爲另一個。 –

回答

0

如果有人需要這個這裏是我做到了一個完整的例子。

創建一個文本框(名爲 「txtCode」)和按鈕(名稱爲 「cmdGenerate」)的形式。

- 如何工作:您輸入將生成的.exe包含的代碼,然後只需按cmbButton。之後,生成文件.exe,並在啓動時執行與任何其他應用程序一樣的命令。

這是文件的生成方法:

Public Sub generateFile() 

    Dim codeProvider As New VBCodeProvider() 
    Dim icc As ICodeCompiler = codeProvider.CreateCompiler 
    Dim Output As String = "C:\Program Files\MyApp.exe" 


    Dim parameters As New CompilerParameters() 
    Dim results As CompilerResults 

    'Make sure we generate an EXE, not a DLL 
    parameters.GenerateExecutable = True 
    parameters.OutputAssembly = Output 
    parameters.CompilerOptions = ("/target:winexe" & " " & "/win32icon:" & """") & "C:\Program Files\MyIcons\Icon.ico" & """" 

    results = icc.CompileAssemblyFromSource(parameters, txtCode.Text) 

    If results.Errors.Count > 0 Then 
     'There were compiler errors 
     Dim CompErr As CompilerError 
     For Each CompErr In results.Errors 
      MessageBox.Show(
       "Line number " & CompErr.Line & 
       ", Error Number: " & CompErr.ErrorNumber & 
       ", '" & CompErr.ErrorText & ";" & 
       Environment.NewLine & Environment.NewLine) 
     Next 
    Else 

     'Successfull Compile 
     MessageBox.Show("Your file is successfully generated!", "Success") 
    End If 

End Sub 

接着,就調用該方法,你已經完成了書面方式txtCode文本框裏面的代碼之後。

裏面txtCode進入的代碼示例是:

Imports System 
Imports System.Diagnostics 

Module Module1 

    Sub Main() 

     Dim CmdStr As String = "CMD ARGUMENTS----" 
     Dim startInfo As New ProcessStartInfo("CMD.EXE") 
     startInfo.WindowStyle = ProcessWindowStyle.Minimized 
     startInfo.WindowStyle = ProcessWindowStyle.Hidden 
     startInfo.CreateNoWindow = True 
     startInfo.UseShellExecute = False 
     startInfo.Arguments = CmdStr 
     Process.Start(startInfo) 

    End Sub 

End Module