HOW TO GET HANDLE TO THE WINDOW IN WPF?

Pravesh Singh

Total Post:101

Points:709
Posted by  Pravesh Singh
WPF 
WPF
 1716  View(s)
Ratings:
Rate this:

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?

Thanks.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: How to get handle to the window in wpf?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!