How can I tell if a window has focus? (Win32 API)

Solution 1:

GetActiveWindow will return the top-level window that is associated with the input focus. GetFocus will return the handle of the window that has the input focus.

This article might help:
http://www.microsoft.com/msj/0397/Win32/Win320397.aspx

Solution 2:

Besides gkrogers answer using GetActiveWindow, you can also maintain a boolean variable for the window you want to know if it has focus or not by trapping the WM_SETFOCUS and WM_KILLFOCUS events, or WM_ACTIVATE:

WndProc() ..
case WM_SETFOCUS:
  puts( "Got the focus" ) ;
  break ;

case WM_KILLFOCUS:
  puts( "Lost the focus" ) ;
  break;

case WM_ACTIVATE:
  if( LOWORD(wparam) == WA_INACTIVE )
    puts( "I AM NOW INACTIVE." ) ;
  else // WA_ACTIVE or WA_CLICKACTIVE
    puts( "MEGAZORD ACTIVATED kew kew kew (flashy-eyes)" ) ;
  break ;

Solution 3:

Do you really mean "focus" or do you mean "active?"

One window has the focus -- the one that's first in line to get keyboard events. The outer window (that the user can drag around the screen) is "active" if one of its subwindows has the focus, but it might or might not have focus itself.

Solution 4:

Use GetForegroundWindow function to get the Hwnd that you are focusing right now. Then you just need to compare it to the window of your application to check whether it contains focus or not.