title: How can I capture window focus change event with c#
body: <p>I want to build an application to monitor all running windows focus change event. I know WM_KILLFOCUS (0x0008) and WM_SETFOCUS(0x0007) and when window lost focus or get focus, the message will be sent. with help of spy++, I get output like this:</p>
  
  <p>&lt;00001> 0005069A S WM_SETFOCUS hwndLoseFocus:(null)</p>
  
  <p>&lt;00002> 0005069A R WM_SETFOCUS</p>
  
  <p>&lt;00003> 0005069A S WM_KILLFOCUS hwndGetFocus:(null)</p>
  
  <p>&lt;00004> 0005069A R WM_KILLFOCUS</p>
  
  <p>&lt;00005> 00010096 S WM_SETFOCUS hwndLoseFocus:(null)</p>
  
  <p>&lt;00006> 00010096 R WM_SETFOCUS</p>
  
  <p>I tried to write following c# code to make it work in my winfrom application:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct NativeMessage
  {
   public IntPtr handle;
   public uint msg;
   public IntPtr wParam;
   public IntPtr lParam;
   public uint time;
   public System.Drawing.Point p;
  }
  [DllImport("user32.dll")]
  public static extern sbyte GetMessage(out NativeMessage lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
  
  NativeMessage msg = new NativeMessage();
          sbyte ret;
          while ((ret = GetMessage( out msg, IntPtr.Zero, 0, 0)) != -1)
          {
              if (ret == -1)
              {
                  //-1 indicates an error
              }
              else
              {
                  if (msg.msg == 0x0008 || msg.msg == 0x0007)
                  {
                      this.textBox1.Text = "ret is: " + ret;
                  }
              }
          }
  </code></pre>
  
  <p>Unfortunately, I never get message WM_KILLFOCUS and WM_SETFOCUS. </p>
  
  <p>I actually want to trigger an event in my application when I find the get/lost focus event happens in all running windows. How can I make it work? </p>
  
  <p>Thanks.</p>