简体   繁体   中英

Launch a WPF application in a DLL from a console application exe

Currently I have two separate C# projects under the same solution, let's call it Window.exe and Console.exe. Window.exe is a WPF MVVM application that works well standalone.

To eliminate one small issue, my goal is to convert Window.exe into Window.dll, and then use Console.exe to load Window.dll. I tried to call App.Run(), or move the routine in App_Startup, that is used to launch the main window onto a separate method and called it. The new thread that runs Window.dll couldn't really last. It was able to populate the GUI when I stepped into it in debug, but I could not interact with it.

Any ideas on how I should proceed?

I was able to accomplish this by doing two things:

  1. You need to mark the Main method in your console applicaiton as an STAThread method because the UI will need to be on an STA thread. If you don't, you'll get an exception when the constructor for the main window is called.

  2. Make sure you also call InitializeComponent() before Run(). If you don't, the app will run, but the window won't have been set up first.

I was able to get this to work in a solution where I, as well, have a WPF main application and console application for testing things:

[STAThread]
static void Main(string[] args)
{
   WpfApp.App app = new WpfApp.App();
   app.InitializeComponent();
   app.Run();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM