我想知道是否有办法来执行Textbox1中的脚本 就像你在textbox1
中编写这段代码一样msgbox("Hello World")
当您单击按钮或按Enter键时,它将运行您在Textbox1中编写的命令/脚本
答案 0 :(得分:4)
是的,你可以。这有点乱,从网上各种文章拼凑而成,但你得到了一般的想法...
Imports System.IO
Imports System.Reflection
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports Microsoft.VisualBasic
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' read code from textbox
Dim Code As String = TextBox1.Text
' clear output textbox
TextBox2.Clear()
' create fully functional assembly string
Code = ("Imports System" & vbCrLf &
"Imports System.Windows.Forms" & vbCrLf &
"Imports Microsoft.Visualbasic" & vbCrLf &
"Public Class TempClass" & vbCrLf &
"Public Sub MyCode(ByVal Textbox2 As TextBox)" & vbCrLf &
Code & vbCrLf &
"End Sub" & vbCrLf &
"End Class")
' create the compiler
Dim vbProv = New VBCodeProvider()
' create parameters to pass to the compiler
Dim vbParams = New CompilerParameters()
' add referenced assemblies.
vbParams.ReferencedAssemblies.Add("System.dll")
vbParams.ReferencedAssemblies.Add("System.Windows.Forms.dll")
vbParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
' generate an assembly in memory
vbParams.GenerateExecutable = False
vbParams.GenerateInMemory = True
' give it a name
vbParams.OutputAssembly = "MyCode"
' compile the code and get the compiler results
Dim compResults = vbProv.CompileAssemblyFromSource(vbParams, Code)
' check for compile errors
If compResults.Errors.HasErrors Then
Dim ErrorMsg As String = compResults.Errors.Count.ToString & " Errors:"
For x As Integer = 0 To compResults.Errors.Count - 1
ErrorMsg = ErrorMsg & vbCrLf & "Line: " & compResults.Errors(x).Line.ToString & " - " + compResults.Errors(x).ErrorText
Next
TextBox2.Text = ErrorMsg & vbCrLf & vbCrLf + Code
Else
' create instance of the temporary compiled class
Dim obj As Object = compResults.CompiledAssembly.CreateInstance("TempClass")
' use textbox 2 for output
Dim args() As Object = {Me.TextBox2}
Try
' execute the code
Dim result As Object = obj.GetType().InvokeMember("MyCode", BindingFlags.InvokeMethod, Nothing, obj, args)
Catch Oops As Exception
' oops
MessageBox.Show(Oops.Message)
End Try
End If
End Sub
End Class
答案 1 :(得分:2)
您正在寻找CodeDOM。这基本上允许您从程序中运行编译器。请注意,用户可以在框中键入任何并使用它来破坏您的程序。