tags:

views:

1282

answers:

2

Hi

Trying to dig into the win32 api from my WPF application (which just runs through the systray).

When clicking on the systray icon, I present the user with a contextmenu, which gains focus over whatever window was topmost.

I want to get a handle to that window (the one, that just lost focus) and have tried with different approaches using

GetForeGroundWindow()
GetTopWindow()
GetDesktopWindow()

To no end however. I'm currently considering iterating through all processes, to get the MainWindowHandles and checking the z-order of each and every window.

But I reckoned that there's an easier/smarter way; simply just one I cannot google or recall from my old Petzold tome.

Another way would be for my systray menu not to gain focus when activated?

Thanks!

A: 

I don't think there is anything simpler than your described z-index iteration. Your systray menu has to get focus, because otherwise people won't be able to use it (for example, with keyboard). And if it gets focus, then it becomes the foreground window, so the old foreground window is left without any distinction from any other inacitve window in the system. Truly, the z-index check IMHO is the only way.

Vilx-
+1  A: 

You could get the topmost window before opening the menu, regardless of the menu item the user will eventually choose.

Then, if you need the topmost window, you could just use the value you got before opening the menu.

DR
Of course! Trying to find the focus event to override, but currently just making the check with a DispatcherTimer.
Chrysaor