title: Win32 ListView - handle invalid after LVM_INSERTITEM
body: <p>I have a problem a window handle (window class = WC_LISTVIEW) after calling</p>
  
  <pre><code>SendMessage(hListView_, LVM_INSERTITEM , 0, (LPARAM)&amp;lvItem);
  </code></pre>
  
  <p>where</p>
  
  <pre><code>hListView_
  </code></pre>
  
  <p>is a handle to a list view window and</p>
  
  <pre><code>lvItem
  </code></pre>
  
  <p>is an LVITEM structure. The following code</p>
  
  <pre><code>std::cout &lt;&lt; "Last error: " &lt;&lt; GetLastError() &lt;&lt; std::endl;
  SendMessage(hListView_, LVM_INSERTITEM , 0, (LPARAM)&amp;lvItem);
  std::cout &lt;&lt; "Last error: " &lt;&lt; GetLastError() &lt;&lt; std::endl;
  </code></pre>
  
  <p>prints</p>
  
  <pre><code>Last error: 0
  Last error: 6
  </code></pre>
  
  <p>According to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382%28v=vs.85%29.aspx" rel="nofollow">Win32 System Error Codes</a> code 6 means ERROR_INVALID_HANDLE.</p>
  
  <p>I create the LVITEM structure as follows:</p>
  
  <pre><code>// define a char-buffer
  char szBuffer[256];
  szBuffer[0] = '\0';
  
  // create new list view item
  LVITEM lvItem;
  lvItem.cchTextMax = 256;
  lvItem.mask = LVIF_TEXT;
  lvItem.iItem = 0;
  lvItem.stateMask = 0;
  lvItem.state = 0;
  lvItem.iSubItem = 0;
  snprintf(szBuffer, 256, "%s", myString.c_str());
  lvItem.pszText = szBuffer;
  </code></pre>
  
  <p>This code is called from the same thread which created the window (list view).
  Also note that I have</p>
  
  <pre><code>lvItem.iSubItem = 0;
  </code></pre>
  
  <p>which is required according to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb761107(v=vs.85).aspx" rel="nofollow">LVM_INSERTITEM</a>. The list view is empty prior to this call. Moreover, I can actually see the value being inserted in the list view (i.e. I can see the item in the list view in the GUI).
  However, when I try to use the window handle after this the application crashes (no exception, just crashes).</p>
  
  <p>Greatful for any hints on what might cause this.</p>
  
  <p>Thank you.</p>