Thursday 23 June 2016

c# run external program, method in program

http://stackoverflow.com/questions/878632/best-way-to-call-external-program-in-c-sharp-and-parse-output

Reflection, activator.createinstance

private void button1_Click(object sender, EventArgs e)
        {
            var assembly = Assembly.Load("CPRG253.School.Domain");

            var mgr = assembly.CreateInstance("CPRG253.School.Domain.XmlStudentManager");

            var t = mgr.GetType();

            var items = t.InvokeMember("GetAll", BindingFlags.InvokeMethod, null, mgr, null);
            uxTypes.Items.Clear();
            uxTypes.DataSource = items;
            uxTypes.DisplayMember = "LastName";
        }
----------------------------------------------------------------------------------
        private void button2_Click(object sender, EventArgs e)
        {
            var assembly = Assembly.LoadFile(@"C:\CPRG253\CPRG253.RealEstate.Domain.dll");
            var t = assembly.GetType("CPRG253.RealEstate.Domain.FileAccessObject");
            var obj = Activator.CreateInstance(t);

            var m = t.GetMethod("GetCities");

            var cities = m.Invoke(obj, null);

            uxTypes.Items.Clear();
            uxTypes.DataSource = cities;
            uxTypes.DisplayMember = "Name";
        }
-----------------------------------------------------------------
public class FormLoader
    {
        public static Form CreateForm(string formName, 
                                      Form mdiParent, 
                                      object[] formParameters)
        {
            var assembly = Assembly.GetCallingAssembly();
            var t = assembly.GetType(formName);
            var parts = formName.Split('.');
            var fName = parts[parts.GetUpperBound(0)];
            Form frm = mdiParent.MdiChildren.SingleOrDefault(f => f.GetType().Name == fName);

            if(frm == null || frm.IsDisposed)
            {
                frm = (Form)Activator.CreateInstance(t, formParameters);
                frm.MdiParent = mdiParent;
            }
            frm.Show();
            frm.BringToFront();
            return frm;
        }
    }
--------------------------------------------------------------------
  private void child1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormLoader.CreateForm("FormsLoaderDemo.ChildForm1", this, null);
        }

        private void child2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormLoader.CreateForm("FormsLoaderDemo.ChildForm2", this, new object[] { "UPDATE FORM" });
        }

No comments:

Post a Comment