title: How to find the active window
body: <p>I need to find the active window in a particular process. The goal of this is to get the name of the active window/document, even if its parent application has a multiple document interface.</p>
  
  <p>To get the active process, I'm using GetGUIThreadInfo along with GetCurrentThreadId from user32.dll. Here's the pertinent code:</p>
  
  <pre><code>Private Type RECT
      Left As LongPtr
      Top As LongPtr
      Right As LongPtr
      Bottom As LongPtr
  End Type
  
  Private Type GUITHREADINFO
  
      cbSize As LongPtr
      flags As LongPtr
      hwndActive As LongPtr
      hwndFocus As LongPtr
      hwndCapture As LongPtr
      hwndMenuOwner As LongPtr
      hwndMoveSize As LongPtr
      hwndCaret As LongPtr
      rcCaret As RECT
  
  End Type
  
  Private Declare PtrSafe Function GetWindowThreadProcessId Lib "user32" ( _
      ByVal hWnd As LongPtr) As LongPtr
  
  Private Declare PtrSafe Function GetGUIThreadInfo Lib "user32" _
      (ByVal dwthreadid As LongPtr, _
      lpguithreadinfo As GUITHREADINFO) As LongPtr
  
  Sub MyFunction()
  
      Dim strWindowTitle As String
      strWindowTitle = Space(30)
  
      Dim GUIInfo As GUITHREADINFO
      GUIInfo.cbSize = LenB(GUIInfo)
  
      Call GetGUIThreadInfo(GetCurrentThreadId, GUIInfo)
      Call GetWindowText(GUIInfo.hwndActive, strWindowTitle, 30)
  
      Debug.Print strWindowTitle
  
  End Sub
  </code></pre>
  
  <p>I tried changing types around, using different methods to get the active thread ID. The output is blank.</p>
  
  <p>Printing GUIInfo.hwndActive gives me 0.</p>
  
  <p>The current thread ID is found, but I'm doing something wrong in the GetGUIThreadInfo function.</p>
  
  <p>I've tried enumerating through the child windows, but it's difficult for me to tell which one of those is active. If there's a function to do this that I've missed, that would probably work as well.</p>
  
  <p>I'm running Outlook 2010 x64 on a 64-bit machine, hence my use of LongPtr.</p>