Solved

Starting a WPF form via Reflection

Posted on 2016-09-01
8
31 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
  • 5
  • 3
8 Comments
 
LVL 69

Expert Comment

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

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 69

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
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 41780059
1
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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
 

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
 

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
 

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now