Solved

Starting a WPF form via Reflection

Posted on 2016-09-01
8
76 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
Increase Agility with Enabled Toolchains

Connect your existing build, deployment, management, monitoring, and collaboration platforms. From Puppet to Chef, HipChat to Slack, ServiceNow to JIRA, Splunk to New Relic and beyond, hand off data between systems to engage the right people.

Connect with xMatters.

 
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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

717 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