我需要创建一个VB.NET应用程序,它接受 Windows窗体应用程序的源代码并编译它。我使用此link作为参考。
我要创建的Windows窗体应用程序
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox("test")
End Sub
结束班
我编译代码的VB.NET应用程序
Imports System.IO
Imports System.Reflection
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports Microsoft.VisualBasic
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim codeProvider As New VBCodeProvider()
Dim icc As ICodeCompiler = codeProvider.CreateCompiler
Dim Output As String = "Out.exe"
Dim ButtonObject As Button = CType(sender, Button)
textBox2.Text = ""
Dim parameters As New CompilerParameters()
Dim results As CompilerResults
'Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = True
parameters.OutputAssembly = Output
results = icc.CompileAssemblyFromSource(parameters, textBox1.Text)
If results.Errors.Count > 0 Then
'There were compiler errors
textBox2.ForeColor = Color.Red
Dim CompErr As CompilerError
For Each CompErr In results.Errors
textBox2.Text = textBox2.Text &
"Line number " & CompErr.Line &
", Error Number: " & CompErr.ErrorNumber &
", '" & CompErr.ErrorText & ";" &
Environment.NewLine & Environment.NewLine
Next
Else
'Successful Compile
textBox2.ForeColor = Color.Blue
textBox2.Text = "Success!"
'If we clicked run then launch the EXE
If ButtonObject.Text = "Run" Then Process.Start(Output)
End If
End Sub
Textbox1.text
包含我提供的第一个代码。当我运行程序时,它给了我这个错误
Line number 0, Error Number: BC30420, ''Sub Main' was not found in 'Out'.;
Line number 2, Error Number: BC30002, 'Type 'EventArgs' is not defined.;
Line number 3, Error Number: BC30451, ''MsgBox' is not declared. It may be inaccessible due to its protection level.;
Line number 3, Error Number: BC32017, 'Comma, ')', or a valid expression continuation expected.;
答案 0 :(得分:4)
嗯,你错过了很多东西。
在您传递给CompilerParameters
的{{1}}中,您必须指定目标exe-type,默认为“/ target:exe”,这意味着Console可执行文件(然后编译器尝试查找)输入点的 Sub Main(),因此您必须为WindowsForms项目指定“/ target:winexe”。
您还必须在要编译的源代码中指定所需的CodeDomProvider
...否则将无法解析,并且对于源代码所需的.NET程序集引用相同,您必须指定所有这些都在你的Imports
。
最后你应该指定主类的名称,然后你就可以编译它了。
我将展示一个可以适应/替换当前源代码的工作示例:
CompilerParameters