title: How to globally detect active window change in vb.net?
body: <p>Goal: To make use of windows events/hooks to immediately detect Windows foreground window changing (focus change) WITHOUT using a timer. This is for a global macros program, where I want specific keystrokes/mousebutton clicks to register events only if a certain window is active (rather than checking the foreground window every time a key or mousebutton is pressed).</p>
  
  <p>I know how to use GetForegroundWindow to get the handle of the foreground window and GetActiveWindowText to get the title, and I know I COULD use these in a timer to keep it constantly updated. However, I would really rather make use of windows messages to accomplish this if possible (other related topics on this site have made use of timers, not windows messages).</p>
  
  <p>I have tried WM_ACTIVATE, WM_ACTIVATEAPP, and WM_SHOWWINDOW but these don't appear to be global (I think only low-level hooks like keyboard hooks can be global), so they do not fire if I change window focus such as from Google Chrome to Calculator or Notepad. Do I need to register a hook or something in order to use a global form of these messages, or is that actually not possible?</p>
  
  <p>Goal would be something like this:</p>
  
  <pre><code>    Protected Overrides Sub WndProc(ByRef m As Message)
      MyBase.WndProc(m)
      Select Case m.Msg
         Case WM_ACTIVATE 'Whatever message that can be used to determine windows focus change
              Dim caption As New System.Text.StringBuilder(256)
              Dim hWnd As IntPtr = GetForegroundWindow()
              GetActiveWindowText(hWnd, caption, caption.Capacity)
              Me.Text = caption.ToString
      End Select
  End Sub
  </code></pre>