<p>Is there a way to track which window currently has keyboard focus. I could handle WM_SETFOCUS for every window but I'm wondering if there's an alternative, simpler method (i.e. a single message handler somewhere).</p>

<p>I could use OnIdle() in MFC and call GetFocus() but that seems a little hacky.</p>

[{'answer_id': 44244, 'author': 'roomaroo', 'author_id': 3464, 'author_profile': 'https://Stackoverflow.com/users/3464', 'pm_score': 2, 'selected': False, 'text': '<p>How about the Win32 <a href="http://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx" rel="nofollow noreferrer">GetForegroundWindow</a>?</p>\n'}, {'answer_id': 44341, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>So from the way you worded the question I\'m inferring that you want to have an event handler which is invoked whenever focus switches between windows. You want to be notified, rather than having to poll.</p>\n\n<p>I actually don\'t think calling GetFocus from OnIdle is that much of a hack - sure it\'s polling, but it\'s low-overhead polling without side effects - but if you really want to track this, <a href="http://msdn.microsoft.com/en-us/library/ms997537.aspx" rel="noreferrer">Windows Hooks</a> are probably your best choice. Specifically you can install a CBT hook (WH_CBT) and listen for the HCBT_SETFOCUS notification.</p>\n\n<blockquote>\n  <p>Windows calls the WH_CBT hook with this hook code when Windows is about to set the focus to any window. In the case of thread-specific hooks, the window must belong to the thread. If the filter function returns TRUE, the focus does not change.</p>\n</blockquote>\n\n<p>You could also do with with a WH_CALLWNDPROC hook and listen for the WM_SETFOCUS message.</p>\n\n<p>Depending on whether you make it a global hook, or app-local, you can track focus across all windows on the system, or only the windows owned by your process.</p>\n'}, {'answer_id': 44345, 'author': 'hometoast', 'author_id': 2009, 'author_profile': 'https://Stackoverflow.com/users/2009', 'pm_score': 0, 'selected': False, 'text': '<p>You could monitor messages for the <a href="http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputmessages/wm_activate.asp?frame=true" rel="nofollow noreferrer">WM_ACTIVATE</a> event.</p>\n\n<p><a href="http://blogs.msdn.com/jfoscoding/archive/2006/08/02/686141.aspx" rel="nofollow noreferrer">ref</a></p>\n'}, {'answer_id': 44371, 'author': 'JosephStyons', 'author_id': 672, 'author_profile': 'https://Stackoverflow.com/users/672', 'pm_score': 0, 'selected': False, 'text': '<p>Well, this may not be very graceful... but you can retrieve the <em>current</em> focused control pretty easily.  So you might consider setting up a timer that asks every 1/2 second or so "Where is the current focus?"... Then you can observe changes.  Example Delphi code is below; it should be pretty easy to adapt, since the real work is in the Windows API calls.</p>\n\n<pre><code>&lt;snip&gt;\n\nfunction TForm1.GetCurrentHandle: integer;\nvar\n  activeWinHandle: HWND;\n  focusedThreadID : DWORD;\nbegin\n  //return the Windows handle of the currently focused control\n  Result := 0;\n  activeWinHandle := GetForegroundWindow;\n  focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);\n  if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin\n    try\n      Result := GetFocus;\n    finally\n      AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);\n    end;\n  end;  //if attached\nend;\n\nprocedure TForm1.Timer1Timer(Sender: TObject);\nbegin\n  //give notification if the handle changed\n  //(this code gets fired by a timer)\n  CurrentHandle := GetCurrentHandle;\n  if CurrentHandle &lt;&gt; PreviousHandle then begin\n    Label1.Caption := \'Last focus change occurred @ \' + DateTimeToStr(Now);\n  end;\n  PreviousHandle := CurrentHandle;\nend;\n\n&lt;snip&gt;\n</code></pre>\n'}, {'answer_id': 93406, 'author': 'olorin', 'author_id': 1098074, 'author_profile': 'https://Stackoverflow.com/users/1098074', 'pm_score': 3, 'selected': False, 'text': '<p>There is an easy way using .Net Framework 3.5 : the library <strong>UI Automation</strong> provides an event focus changed that fires every time the focus change to a new control.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.automation.automationfocuschangedeventargs.aspx" rel="nofollow noreferrer">Page on MSDN</a></p>\n\n<p>Sample:</p>\n\n<pre><code>public void SubscribeToFocusChange()\n{\n    AutomationFocusChangedEventHandler focusHandler \n       = new AutomationFocusChangedEventHandler(OnFocusChanged);\n    Automation.AddAutomationFocusChangedEventHandler(focusHandler);\n}\n\nprivate void OnFocusChanged(object sender, AutomationFocusChangedEventArgs e)\n{\n    AutomationElement focusedElement = sender as AutomationElement;\n    //...\n}\n</code></pre>\n\n<p>This api in fact use windows hook behind the scenes to do that. However you have to use the .Net Framework...</p>\n'}, {'answer_id': 838158, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/ms771428.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms771428.aspx</a></p>\n\n<p>Has a window focus tracker sample. </p>\n'}, {'answer_id': 890565, 'author': 'vanmelle', 'author_id': 76365, 'author_profile': 'https://Stackoverflow.com/users/76365', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re programming in .net 3.5, the Automation package olorin mentions is by far the easiest, but beware of using it in a program that itself has a UI, at least if the UI is done in WPF -- the focus tracking hooks get confused by events in its own app, and quickly lock up the UI.  I sent MS a <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=450706" rel="nofollow noreferrer">bug report</a> on it.  I have not observed the same problem using a traditional Windows Forms UI.  You could, of course, put the tracking code in a separate console app and use some kind of ipc to transmit the info you need.</p>\n\n<p>The tempting alternative of using Interop to access the WH_CBT Windows Hook from C# won\'t work -- <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;318804" rel="nofollow noreferrer">the only global hooks you can get at from C# are the mouse and keyboard</a>.</p>\n'}]
['https://Stackoverflow.com/questions/44241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2768/']