Most probably the window you need is not the foreground window. It works in most cases, but can fail to get desired effect when the application runs a dialog.
To do the next step, you should use P/Invoke.
Windows is very naughty, what you thing is obvious may be not what you want.
So here is what you do: call Windows API
GetForegroundWindow
, get some HWND as a return value. Use this HWND value as a parameter of the API
GetLastActivePopup
. Most likely, it will return the same HWND as its parameter, but in certain cases, it will return some other HWND of the windows owned by your foreground windows. This is what's
really on top.
The last step depends on your application. From the previous step you got two window handles; they can be the same or not. You may need both of them or just one of them, depending on what you want to do with them.
[EDIT]
A follow-up comment OP confirm the actually the "last active popup" is what required.
"Active window" means "a popup window holding keyboard focus or having non-popup children, one of them holding keyboard focus". By weird Windows design, it is not always a foreground window. Microsoft… :-)
See for more information:
http://msdn.microsoft.com/en-us/library/ff468919(v=VS.85).aspx[
^].
—SA