Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reliably find the foreground window when it does not have focus

Tags:

c#

interop

So, I thought this would be simple and, well, I was wrong. Here is a simplified description of the problem:

I am writing a small application for our manufacturing folks that will grab a screenshot of the entire desktop as well as the foreground window when they click the application's icon in the system tray. Currently, I am using the Win32 method "GetforegroundWindow" in the MouseMove event of the NotifyIcon to save the foreground window handle and take the screenshot in the Click event.

This does work sometimes, but if I click the icon very quickly I actually capture the task bar instead of the foreground window. I am not sure why this is happening (I do understand that the task bar is a window, I don't understand why sometimes it seems to have focus in MouseMove before I have clicked), and I have had little luck using the EnumWindows method as well, likely because I do not completely understand how it works.

It would seem that, if I were able to get the z position of each window using only the window handle, this would be an easy problem to solve using EnumWindows. I have not found a method to do that however.

So, I ask you guys; how would you write a method to locate the foreground window reliably, given that it may not have focus at the time? Either my google-fu is failing me or the information on this is sparse. Thanks in advance.

like image 201
Ed S. Avatar asked Feb 26 '10 18:02

Ed S.


1 Answers

The taskbar is as valid a foreground window as any. When you click it, it will temporarily be the foreground window. And if you click Start and press Escape for example, it will be the foreground window until you click off of it.

You can probably use GetWindow with HWND_NEXT passing in the window handle of the taskbar.

Nevermind, since the taskbar is a topmost window, GetWindow (or GetNextWindow, etc) will operate differently. I would suggest revisiting the EnumWindows solution which is probably your best bet.

like image 56
Josh Avatar answered Oct 13 '22 00:10

Josh