0

Currently I have a program to display some item information. What I have is a com box to exercise different categories, and one panel to display items per selection in the com box.

I created my own custom control to display, but when I add it to a panel dynamically, it causes a Win32 Exception which is Create Window handle Error.

After testing several times, I noticed that once the panel has listed 1800 custom controls in total, the exception occurs. Is there anyone who can resolve this issue? Thanks.

private void DisplayItems(List<ITEM_DATA> ItemList)
{
    DisposeControls();
    int total = ItemList.Count;

    ItemDisplayer itemDisplayer = null;
    Application.DoEvents();
    for (int i = 0; i < total / 4 + 1; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            int m = (i * 4) + j;
            if (m >= total)
            {
                return;
            }
            itemDisplayer = new ItemDisplayer(ItemList[m], ref labItemName);
            itemDisplayer.Size = new Size(240, 80);
            itemDisplayer.Location = new Point(240 * j, 80 * i);
            itemDisplayer.Name = "itemDisplayer" + Convert.ToString(m);
            pnlItems.Controls.Add(itemDisplayer); 
        }
    }
}
reformed
  • 4,505
  • 11
  • 62
  • 88
Jacob_Liu
  • 19
  • 3
  • The total number of windows that can be created by *all* of the programs you use has a hard upper-limit of 65535. Windows ensures that a program cannot take its unfair share by limiting its total to 10000. You get this exception when you exceed that limit. Maybe you are leaking controls, use Task Manager and add the USER Objects column so you can see the total. But high odds that you need to write smarter code, 1800 is already pretty unreasonable. – Hans Passant Jul 26 '16 at 16:10
  • yes, i followed your suggestion. The problem is User Object reached 10000. Any idea how to resolve? Thanks – Jacob_Liu Jul 26 '16 at 17:18

1 Answers1

1

Just want to confirm. After spend a while to figure out where this issue happened. I realized that the User Object has reached the limit 10000. And i just resolved that problem by dispose user control properly.

I re-implement dispose method in my custom control class.

 // Flag: Has Dispose already been called?
   bool disposed = false;
   // Instantiate a SafeHandle instance.
   SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         handle.Dispose();
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.
      //
      disposed = true;
   }

According to enter link description here

Jacob_Liu
  • 19
  • 3