I was wondering if there is a way to excute a Script that is in Textbox1 Like you write this code inside textbox1
msgbox("Hello World")
and when you click on the button or press enter it will run the command/script you wrote in Textbox1
I was wondering if there is a way to excute a Script that is in Textbox1 Like you write this code inside textbox1
msgbox("Hello World")
and when you click on the button or press enter it will run the command/script you wrote in Textbox1
You're looking for CodeDOM. This basically lets you run the compiler from within your program. Be careful, the user could type anything into the box and compromise your program with it.
Yes, you can. This is a bit messy and was cobbled together from various articles on the web, but you get the general idea...
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