Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using Microsoft.CSharp;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Drawing;
public class Program
{
//イベントを含むコード
public static string code =
"using System;" +
"using System.Drawing;" +
"using System.Windows.Forms;" +
"namespace NameSpace" +
"{" +
" class ClassName" +
" {" +
" private Form form;" +
" private int count;" +
" private int r = 255, g = 0, b = 0;" +
" public ClassName(Form _form)" +
" {" +
" form = _form;" +
" count = 0;" +
" form.Click += Click;" +
" }" +
" public void AddEvent()" +
" {" +
" form.GetType()" +
" .GetEvent(\"Paint\")" +
" .AddEventHandler(form," +
" Delegate.CreateDelegate(typeof(PaintEventHandler), this, GetType().GetMethod(\"ExecuteEvent\")));" +
" MessageBox.Show(\"イベントを追加しました\");" +
" }" +
" public void DeleteEvent()" +
" {" +
" form.GetType()" +
" .GetEvent(\"Paint\")" +
" .RemoveEventHandler(form," +
" Delegate.CreateDelegate(typeof(PaintEventHandler), this, GetType().GetMethod(\"ExecuteEvent\")));" +
" MessageBox.Show(\"イベントを削除しました\");" +
" }" +
" public void ExecuteEvent(object sender, PaintEventArgs e)" +
" {" +
" if (r == 255)" +
" {" +
" r = 0;" +
" b = 255;" +
" }" +
" else" +
" {" +
" r = 255;" +
" b = 0;" +
" }" +
" e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(r, g, b)), 0, 0, 640, 480);" +
" }" +
" public void Click(object sender, EventArgs e)" +
" {" +
" if (count % 2 == 0)" +
" {" +
" AddEvent();" +
" }" +
" else" +
" {" +
" DeleteEvent();" +
" }" +
" form.Refresh();" +
" count++;" +
" }" +
" }" +
"}";
public static void Main()
{
var form = new Form();
form.ClientSize = new Size(640, 480);
//コードをコンパイルしてAssemblyを取得
var param = new CompilerParameters();
param.ReferencedAssemblies.AddRange(new[]
{
"mscorlib.dll", "System.dll", "System.Core.dll", "Microsoft.CSharp.dll", "System.IO.dll",
"System.Windows.Forms.dll", "System.Drawing.dll"
});
var assembly = new CSharpCodeProvider()
.CompileAssemblyFromSource(param, code)
.CompiledAssembly;
//Extensionの型情報を取得
var dataType = assembly.GetType("NameSpace.ClassName");
//formをコンストラクタの引数としてインスタンスを作成
dynamic instance = Activator.CreateInstance(dataType, form);
//イベントを追加されたフォームを起動
Application.Run(form);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.