I need to run code from a text file, in the context of the current form (code). One of the requirements is to have the code create and add a new control to the current form.
For example, in Form1.cs:
using System.Windows.Forms;
...
public int[] someCoords = { 20, 10 };
public string someImportantString = "Hello";
public void SayHello() {
MessageBox.Show("Hello world.");
}
private void runCodeInForm() {
// theCode will be read from a text file
string theCode = @"
// Has System.Windows.Forms already added in form
Button newButton = new Button();
newButton.Text = someImportantString; // Hello
newButton.Location = new Point(someCoords[0], someCoords[1]); // 20, 10
// Add this button to the current form
this.Controls.Add(newButton);
this.SayHello(); // Says hello. Just an example function.
";
// Execute theCode in the current form
CodeRunner.Execute(theCode, this);
}
I have tried using CSharpCodeProvider, but it seems like this can only compile the code as a separate program.
I would like this because I want the user to be able to change this code (text file) to what they would like. It is not specifically just for creating controls, but that functionality will be needed.
I am not worried about the security of the program.