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

a 夏天 提交于 2019-11-27 13:33:37

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

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_ACTIVE )
    puts( "MEGAZORD ACTIVATED kew kew kew (flashy-eyes)" ) ;
  else 
    puts( "I AM NOW INACTIVE." ) ;
  break ;

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.

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.

For multiple modeless children: Within the Child you could save the focus, 13/08/19 VS2017. You can save the focus so the parent knows which modeless child was clicked on.

In the childs callback handler:

case WM_CHILDACTIVATE: //only gets called when the child border is click on.
    //CurrentFocus = hDlg; //example : can save the focus globally for parent usage.
    //Beep(2000, 250); // so you can test
break;

case WM_GETMINMAXINFO: //gets called when child window is being moved or sized.
        //Beep(2000, 250);
break;

case WM_LBUTTONDOWN:  //Only called when cursor is inside the child client area
    //CurrentFocus = hDlg; // following the focus.
    //Beep(2000, 250);
break;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!