Advertise with us

How to get handle to the window in wpf?

I got a WPF project, which is compiled into a dll and will be called from another application. That's how it is set up. In this WPF project I need to pop up a customized message box from the view model of the main window to show messages to the user. This customized message box requires a Window parameter. That's how it is.

For a WPF application, Application.Current.MainWindow will get me what I need. But here it is a dll, so Application.Current is null, and leads to run time exception. I also tried something like Window.GetWindow(this). Here it is not working, because 'this' is the view model, so it won't give me the handle of the main window.

What else can I try to get the handle of the main window here?


Last updated:9/23/2013 6:58:38 AM

1 Answers

Sumit Kesarwani
Sumit Kesarwani

Hi Pravesh,

Once you get the application dll, and assuming you know the window's name, you can get and instaniate it through reflection

string myWpfAssemblyPath = ""; // Enter the path to your application here

Assembly wpfAppAssembly = Assembly.Load(myWpfAssemblyPath);

var MainWindow = (Window)wpfAppAssembly.CreateInstance("myMainWindow");

Note that this will create a new instance of the window, and not get you a handle of a window that is already running. to get a window handle that is already instansiated, you could use WIN32 API.