lundi 20 avril 2015

CSharpCodeProvider add control to form

I just went into using the CSharpCodeProvider with an example from CodeDom Compiler for C#. Away from what this guy did I changed my code for compiling to windows forms instead of a console application.

My current problem is I cant add any controls to my form. They just wont show up.

Source to compile: (Which isnt working as expected)

using System;
using System.Windows.Forms;
using System.Timers;
using System.Drawing;

namespace buildedApp
{    
    public class Sample
    {
        public static Label labelCounter = new Label();
        public static Form mainForm = new Form();

        static void Main()
        {
            Application.EnableVisualStyles();

            labelCounter.Text = "Hello"; // Not showing up !
            labelCounter.Location = new Point(100, 100);
            labelCounter.Enabled = true;
            labelCounter.Visible = true;

            mainForm.Text = "Running app";
            mainForm.ShowDialog();

            mainForm.Controls.Add(labelCounter);
        }
    }
}

Beside that here is my compiling app:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Builder
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void Compile(string source, string file)
        {
            var prov = new Dictionary<string, string>();
            prov.Add("CompilerVersion", "v2.0");
            CSharpCodeProvider c = new CSharpCodeProvider();
            ICodeCompiler comp = c.CreateCompiler();

            CompilerParameters param = new CompilerParameters();
            param.GenerateExecutable = true;
            param.OutputAssembly = file + ".exe";
            param.ReferencedAssemblies.Add("System.dll");
            param.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            param.ReferencedAssemblies.Add("System.Drawing.dll");
            // Windows Forms - not console //
            param.CompilerOptions = "/target:winexe";

            CompilerResults results = comp.CompileAssemblyFromSource(param, CobeyBuilder.Properties.Resources.source);

            // Shows compiler-errors at runtime // 
            foreach(CompilerError CompErr in results.Errors)
            {
                MessageBox.Show("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Compile("source.cs","text");
        }
    }
}

Result
enter image description here

I guess its a small stupid mistake anywhere...

Every help appreciated in here.
Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire