title: C# Win32 Interop Crashes when Enumerating Window Handles
body: <p>I have a C# wrapper for some Win32 operations involving window handles, but I am experiencing an unexpected crash, with no details, when I call a Win32 function.</p>
  
  <p>Interestingly, this whole code sample works fine when the class is constructed (at application init time), but later fails when the same <code>buildCache()</code> method is called.</p>
  
  <p>Here is the relevant code:</p>
  
  <pre><code>public delegate bool CallBack(int hWnd, int lParam);
  
  public class Win32Interop {
      private Dictionary&lt;int, string&gt; windowCache = new Dictionary&lt;int, string&gt;();
  
      public Win32Interop() {
          buildCache();
      }
  
      public void buildCache() {
          windowCache.Clear();
  
          CallBack hWndCacher = new CallBack(saveHWndHandler);
          EnumWindows(hWndCacher, 0);
      }
  
      public void doThings(string title, uint message, bool rebuildCache = false) {
      //Use the window title to get its handle
          int hWnd = titleToHWnd(title, rebuildCache);
          SendMessage(hWnd, message, 0, 0);
      }
  
      private bool saveHWndHandler(int hWnd, int lParam) {
          if(IsWindow(hWnd) != 0) {       / ***** CRASHES HERE ***** /
              int length = GetWindowTextLength(hWnd);
              StringBuilder title = new StringBuilder(length + 1);
  
              GetWindowText(hWnd, title, title.Capacity);
              string formatted = title.ToString().Trim();
  
              windowCache.Add(hWnd, formatted);
          }
  
          return true;
      }
  
      private int titleToHWnd(string title, bool rebuildCache = false) {
          if(rebuildCache)
              buildCache();
  
          if(windowCache.ContainsValue(title)) {
              return windowCache.FirstOrDefault(x =&gt; x.Value.Contains(title)).Key;
          } else {
              throw new KeyNotFoundException(string.Format("\"{0}\" is not a window title which is available in the cache.", title));
          }
      }
  
      #region Win32 API Functions
      [DllImport("user32.dll")]
      private static extern int EnumWindows(CallBack lpEnumFunc, int lParam);
  
      [DllImport("user32.dll")]
      private static extern int GetWindowText(int hWnd, StringBuilder lpString, int maxCount);
  
      [DllImport("user32.dll")]
      private static extern int GetWindowTextLength(int hWnd);
  
      [DllImport("user32.dll")]
      private static extern int IsWindow(int hWnd);
  
      [DllImport("user32.lib")]
      private static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
      #endregion
  }
  </code></pre>
  
  <p>Inside of the <code>saveHWndHandler()</code> method, I've marked the line were the debugger shows execution stops. Interestingly, there are usually ~300 window handles returned by <code>EnumWindows()</code>, and it always crashes on iteration number 45 or 46. The window handle it crashes on is a reasonable value, such as 12345.</p>
  
  <p>According to <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633528%28v=vs.85%29.aspx" rel="nofollow">MSDN</a>, <code>IsWindow()</code> should return <code>0</code>, if a window was not associated with the handle, not crash the thread.</p>
  
  <p>Does anyone know why this is happening? There isn't a thrown exception, or any details in the Windows event log.</p>
  
  <p>Thank you.</p>
  
  <blockquote class="spoiler">
    <p> For those who don't want to figure out the buildCache() process works:
   (1.) When <code>buildCache()</code> is called, the dictionary of <code>&lt;HWnd, Title&gt;</code> values is cleared.
   (2.) The Win32 function <code>EnumWindows()</code> is called, which calls the <code>saveHWndHandler()</code> method for each window handle.
   (3.) <code>saveHWndHandler()</code> will check if the current window handle still exists, the call another Win32 to function to get the window title from the handle.
   (4.) The title and window handle are added to the dictionary.</p>
  </blockquote>