Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Starting a WPF form via Reflection

Posted on 2016-09-01
8
Medium Priority
?
102 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
Technology Partners: 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 2000 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

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

604 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