?
Solved

Starting a WPF form via Reflection

Posted on 2016-09-01
8
Medium Priority
?
80 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
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 
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

TCP/IP Network Protocol Cheat Sheet

TCP/IP is a set of network protocols which is best known for connecting the machines that make up the Internet. The truth is that TCP/IP is one of the oldest network protocols and its survival is mainly based on its simplicity and universality.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

801 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