views:

1504

answers:

3

How can I tell if my window is the current active window? My current guess is to do GetForegroundWindow and compare the HWND with that of my window. Is there a better method than that?

I'm using Win32 API / MFC.

+4  A: 

Yes, that's the only way that I'm aware of.

But you have to handle the fact that GFW can return NULL. Typically, this happens when another desktop (e.g. the screen saver desktop) is active. Note that use of a saver password can affect whether a different desktop is used (this is windows version-dependent and I can't remember the details of how different versions work).

Also this code won't work properly in debug mode under Visual Studio, because you will get VS's window handle.

Other than that everything's peachy :-)

Bob Moore
A: 

Yes you are correct unless otherwise you want to check activewindow of every thread.

lakshmanaraj
A: 

I assume that you mean the window which has the input focus when you say "active window"?

In that case, forget the GetForegroundWindow() API. That will return the topmost window - not always the window which has the input focus.

Use GetFocus() instead.

Stefan
That is false: "GetFocus returns the window with the keyboard focus for the current thread's message queue. [...] Use the GetForegroundWindow function to retrieve the handle to the window with which the user is currently working."
Martin Plante
As I said: "if you mean the window which has the input focus".
Stefan
Yes, I mean the window in which the user is working. Thanks
Mark Ingram
GetFocus only works "for the current thread's message queue", that's what I meant. GetForegroundWindow is the API to call, and the name is misleading. That window may not be the topmost in the z-order, but it returns the window which has the global focus. i.e. "is active".
Martin Plante