Solved

Starting a WPF form via Reflection

Posted on 2016-09-01
8
45 Views
Last Modified: 2016-09-02
Is there any special requirement for starting a WPF form via reflection?  I have used reflection within a forms environment but before I started to upgrade what we have to a WPF application I thought it would be prudent to ask the community experts.
0
Comment
Question by:Alyanto
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41779712
it should be the same. I have you tried it and got issues?
0
 
LVL 1

Author Comment

by:Alyanto
ID: 41780045
Hi Eric

I am now yes, I can start a windows form in the library.  The code at the bottom is failing, however if I substitute the line below it works as I might expect.

Substitute
oType = tryit.GetType("Perfcentre.Forms.MainWindow");

Open in new window

with
oType = tryit.GetType("Perfcentre.Forms.FormsWindow");

Open in new window

it works fine.

MainWindow has the XAML extension and the FormsWindow has .cs.  I have considered firing a class to start MainWindow but as yet I have not seen a good example to help me.

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Perfcentre
{
    public class clsMain
    {
       [STAThread]
        static public void Main()
        {
                 
           Assembly tryit;
           tryit = Assembly.Load("Perfcentre.Forms");
           Type oType;
           oType = tryit.GetType("Perfcentre.Forms.MainWindow");
           object DoSomethingClass;

           DoSomethingClass = Activator.CreateInstance(oType);

           Form frm = (Form)DoSomethingClass;
           Application.Run(frm);
        }
    }
}

Open in new window

0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41780055
>>MainWindow has the XAML extension and the FormsWindow has .cs

Does that means that FormsWindow is not a form but just a class? If it is just a class, it won't be castable to a Form!
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 70

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 41780059
1
 
LVL 1

Author Comment

by:Alyanto
ID: 41781185
Actually Eric that is very much the way I was heading for, I will give the code a try today.  I had been looking for such an article., thank you for that.  I will report probably by Monday as to its success.
0
 
LVL 1

Author Comment

by:Alyanto
ID: 41781414
I will post what I did here for future reference.

  • Step 1 Created a solution with a standard forms project in it.
  • Step 2 Added a library project.
  • Step 3 Added references to PresentationCore, PresentationFramework, System.Xaml, and WindowsBase
  • Step 4 Added a WPF user control because that is all that is available I modified the control to have this XAML
<Window x:Class="Reflection_App3.UserControl1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Background="BlueViolet">
    <Grid>

    </Grid>
</Window>

Open in new window


It is not now a WPF form.

  • Step 5 Add to the windows app these references: PresentationFramework, WindowsBase, and the WPF project.
  • Step 6 Add this code to the Program class.

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;

namespace Reflection_App1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            System.Windows.Forms.Application.EnableVisualStyles();
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
            ThreadProc();
            System.Windows.Forms.Application.Run(); // Keep on running!
        }

        private static void ThreadProc()
        {
            if (System.Windows.Application.Current == null)
                new System.Windows.Application();
            try
            {
                string assemblyName = string.Format("{0}\\Reflection_App3.dll", new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName);
                System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    Window wnd = LoadAssembly(assemblyName, "UserControl1");
                    wnd.Show();
                }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Failed to load window from{0} - {1}", "OtherWindow", ex.Message));
                throw new Exception(String.Format("Failed to load window from{0} - {1}", "OtherWindow", ex.Message), ex);
            }
        }

        private static Window LoadAssembly(String assemblyName, String typeName)
        {
            try
            {
                Assembly assemblyInstance = Assembly.LoadFrom(assemblyName);
                foreach (Type t in assemblyInstance.GetTypes().Where(t => String.Equals(t.Name, typeName, StringComparison.OrdinalIgnoreCase)))
                {
                    var wnd = assemblyInstance.CreateInstance(t.FullName) as Window;
                    return wnd;
                }
                throw new Exception("Unable to load external window");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Failed to load window from{0}{1}", assemblyName, ex.Message));
                throw new Exception(string.Format("Failed to load external window{0}", assemblyName), ex);
            }
        }
    }
}

Open in new window


The library hosting the wpf form is called Reflection_App3 and the windows one is Reflection_App1 and the form is called UserControl1.  Obvious I know but sometimes it is worth saying.  The example that Eric gave got me 99% of the way with the very small problem that LoadAssembly was not indicated as static in the example and the steps followed were not there which is why I wrote them here for both my notes and anyone else.
0
 
LVL 1

Author Closing Comment

by:Alyanto
ID: 41781417
Genius mate, quite to the point, as you can see I did a write up so that the steps were clearer than the article you pointed to.  I hope that it helps others if only a little by doing this.  Again many thanks.  Is there an A+ grade perhaps?
0
 
LVL 1

Author Comment

by:Alyanto
ID: 41781419
line in article "It is not now a WPF form" should read "It is now a WPF form".
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PowerShell:  Column widths won't expand 3 47
Regarding swagger API 1 32
SSIS GUID Variable 2 31
powershell try catch  and $ErrorActionPreference = continue 6 22
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question