How to get the highest window if it is modal and inactive

advertisements

I want to prevent users to run my application multiple times on the same machine so I used a solution from this thread: What is the correct way to create a single-instance application?

This works OK, but I have a problem displaying my application when a modal window is opened (for example with view.ShowDialog();). This is a scenario:

  1. User runs my application and opens a modal window.
  2. Then he tries to run my application again, the code in the startup procedure of this second instance of the application finds another application running and broadcasts a WM_SHOWME message to it to show it self. Then the second instance of the application terminates.
  3. The first application receives the WM_SHOWME message (using the solution from How to handle WndProc messages in WPF?). Now it should bring the topmost window to front, and this is my question - how can I get the topmost window of my application if the topmost window is modal and not even active? I tried with the solution from Refer to active Window in WPF? but of course my windows aren't active so this doesn't work.

PS - when the application is running and a modal window is opened and when I hover over the icon in the task bar, then I can see two windows - main window and a modal window. I can click on the main window (which is of course disabled because a modal window is on top of it) and I can click on the modal window also. My solution works just like if I would click on the main window, but I want it be able to activate the topmost window, which is modal in this case.

So, any idea how to bring the topmost modal window (or main window if no modal windows are shown) to the front?


The behavior as described in the question indicates that the main window is not owning the dialog.

Note that when a dialog is owned by a (main) window, then the window cannot cover the dialog (the dialog will normally always stay on top of the window). This also has the effect that when bringing the window to the front, the dialog will also be brought to the front on top of the window -- which neatly will solve the problem you have.

Setting the owner for your dialog (modal window) is rather easy. Simply set its Owner property to you main window before showing the dialog, similar to this example:

Window modalWindow = ... create modal window instance
modalWindow.Owner = mainWindow;
modalWindow.ShowDialog();

(Side note: If it is also desired to have only the icon/thumbnail of the main window appear in the task bar, then the ShowInTaskbar property of the modal window should be set to false.)