Error create windows handle

Winforms issue — Error creating window handle [duplicate]

We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.

10 Answers 10

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns. Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you’ve got UI components that you think are cleaned up but haven’t been Disposed.

Here’s a link about this that might be helpful.

The windows handle limit for your application is 10,000 handles. You’re getting the error because your program is creating too many handles. You’ll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you’re calling the dispose method on controls if you’re removing them from a form before the form closes (otherwise the controls won’t dispose). You’ll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..

See this post of mine about «Error creating window handle» and how it relates to USER Objects and the Desktop Heap. I provide some solutions.

This problem is almost always related to the GDI Object count, User Object count or Handle count and usually not because of an out-of-memory condition on your machine.

When I am tracking one of these bugs, I open ProcessExplorer and watch these columns: Handles, Threads, GDI Objects, USER Objects, Private Bytes, Virtual Size and Working Set.

(In my experience, the problem is usually an object leak due to an event handler holding the object and preventing it from being disposed.)

Well, in my case it was definitely the USER Objects that were out of control. I looked in the Windows Task Manager and sure enough, the USER Objects count was at 10’000 exactly.

I am dynamically embedding property and list sheets in Tab Pages by setting the Parent property of the property or list sheet’s container panel to that of the Tab Page. I am conditionally recycling or re-creating the property and list sheet forms depending on the type of collection being listed or class type of the object being inspected.

NB: In Delphi, all controls had an Owner and a Parent property. Even if one changed the Parent property of a control, it would still be disposed by its owner when the owning control got destroyed.

“Error Creating Window Handle”

We’re working on a very large .NET WinForms composite application — not CAB, but a similar home grown framework. We’re running in a Citrix and RDP environment running on Windows Server 2003.

We’re starting to run into random and difficult to reproduct «Error creating window handle» error that seems to be an old fashion handle leak in our application. We’re making heavy use of 3rd Party controls (Janus GridEX, Infralution VirtualTree, and .NET Magic docking) and we do a lot of dynamic loading and rendering of content based on metadata in our database.

There’s a lot of info on Google about this error, but not a lot of solid guidance about how to avoid issues in this area.

Does the stackoverflow community have any good guidance for me for building handle-friendly winforms apps?

9 Answers 9

I have tracked down a lot of issues with UIs not unloading as expected in WinForms.

Here are some general hints:

  • alot of the time, a control will stay in use because controls events are not properly removed (the tooltip provider caused us really large issues here) or the controls are not properly Disposed.
  • use ‘using’ blocks around all modal dialogs to ensure that they are Disposed
  • there are some control properties that will force the creation of the window handle before it is necessary (for example setting the ReadOnly property of a TextBox control will force the control to be realized)
  • use a tool like the .Net Memory profiler to get counts of the classes that are created. Newer versions of this tool will also track GDI and USER objects.
  • try to minimize your use of Win API calls (or other DllImport calls). If you do need to use interop, try to wrap these calls in such a way that the using/Dispose pattern will work correctly.
Читайте также:  Как узнать состояние аккумулятора ноутбука windows 10

I had this error when I subclassed NativeWindow and called CreateHandler manually. The problem was I forgot to add base.WndProc(m) in my overriden version of WndProc. It caused the same error

Understanding this error

Troubleshooting this error

You need to be able to reproduce the problem. Here is one way of recording the steps to do that https://stackoverflow.com/a/30525957/495455.

The easiest way to work out what is creating so many handles is to have TaskMgr.exe open. In TaskMgr.exe you need to have the USER Object, GDI Object and Handles columns visible as shown, to do this choose View Menu > Select Columns:

Go through the steps to cause the problem and watch the USER Object count increase to around 10,000 or GDI Objects or Handles reach their limits.

When you see the Object or Handles increase (typically dramatically) you can halt the code execution in Visual Studio by clicking the Pause button.

Then just hold down F10 or F11 to cruise through the code watching when the Object/Handle counts increases dramatically.

The best tool I have found so far is GDIView from NirSoft, it breaks up the GDI Handle fields:

I tracked it down to this code used when setting DataGridViews Column Widths:

This is the stack trace:

at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.ComboBox.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.ComboBox.InvalidateEverything() at System.Windows.Forms.ComboBox.OnResize(EventArgs e) at System.Windows.Forms.Control.OnSizeChanged(EventArgs e) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight) at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height) at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.ComboBox.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified) at System.Windows.Forms.Control.set_Width(Int32 value)

Here is the crux of a helpful article by Fabrice that helped me work out the limits:

«Error creating window handle»
When a big Windows Forms application I’m working on for a client is used actively, users often get «Error creating window handle» exceptions.

Aside from the fact that the application consumes too much resources, which is a separate issue altogether that we are already addressing, we had difficulties with determining what resources were getting exhausted as well as what the limits are for these resources. We first thought about keeping an eye on the Handles counter in the Windows Task Manager. That was because we noticed that some processes tended to consume more of these resources than they normally should. However, this counter is not the good one because it keeps track of resources such as files, sockets, processes and threads. These resources are named Kernel Objects.

The other kinds of resources that we should keep an eye on are the GDI Objects and the User Objects. You can get an overview of the three categories of resources on MSDN.

User Objects
Window creation issues are directly related to User Objects.

We tried to determine what the limit is in terms of User Objects an application can use. There is a quota of 10,000 user handles per process. This value can be changed in the registry, however this limit was not the real show-stopper in our case. The other limit is 66,536 user handles per Windows session. This limit is theoretical. In practice, you’ll notice that it can’t be reached. In our case, we were getting the dreaded «Error creating window handle» exception before the total number of User Objects in the current session reached 11,000.

Читайте также:  Драйвера hp g62 windows 10 все

Desktop Heap
We then discovered which limit was the real culprit: it was the «Desktop Heap». By default, all the graphical applications of an interactive user session execute in what is named a «desktop». The resources allocated to such a desktop are limited (but configurable).

Note: User Objects are what consumes most of the Desktop Heap’s memory space. This includes windows. For more information about the Desktop Heap, you can refer to the very good articles published on the NTDebugging MSDN blog:

What’s the real solution? Be green!
Increasing the Desktop Heap is an effective solution, but that’s not the ultimate one. The real solution is to consume less resources (less window handles in our case). I can guess how disappointed you can be with this solution. Is this really all what I can come up with?? Well, there is no big secret here. The only way out is to be lean. Having less complicated UIs is a good start. It’s good for resources, it’s good for usability too. The next step is to avoid waste, to preserve resources, and to recycle them!

Here is how we’re doing this in my client’s application:

We use TabControls and we create the content of each tab on the fly, when it becomes visible; We use expandable/collapsible regions, and again fill them with controls and data only when needed; We release resources as soon as possible (using the Dispose method). When a region is collapsed, it’s possible to clear it’s child controls. The same for a tab when it becomes hidden; We use the MVP design pattern, which helps in making the above possible because it separates data from views; We use layout engines, the standard FlowLayoutPanel and TableLayoutPanel ones, or custom ones, instead of creating deep hierarchies of nested panels, GroupBoxes and Splitters (an empty splitter itself consumes three window handles. ). The above are just hints at what you can do if you need to build rich Windows Forms screens. There’s not doubt that you can find other approaches. The first thing you should do in my opinion is building your applications around use cases and scenarios. This helps in displaying only what’s needed at a given time, and for a given user.

Of course, another solution would be to use a system that doesn’t rely on handles. WPF anyone?

Error creating window handle before window loads [duplicate]

I have a large windows forms program with a lot of controls. The first window I see when I run it is the Login screen, it only has a combobox, button, textbox and a few labels. When I press the button it loads Form1. Form1, on load automatically creates an instance of Game, which it minimizes and embeds Game into Form1 using this code:

error on this line (for some reason it’s not on the window create line):

Please help, others have said that this is to do with too many windows, but there I’ve tried deleting windows in project and I get the same error.

2 Answers 2

This question appears to already be answered: Error creating window handle

You’re getting the error because your program is creating too many handles. The windows handle limit for your application is 10,000 handles. You’ll need to find the memory leak.

Make sure you are calling Dispose() on forms after you close them and are done, or declare the Form inside using clauses:

Process Explorer or the Windows Task Manager allows you to look at the GDI Objects, Handles, Threads and USER objects. You will have to do to the details tab and select those columns to be viewed (Right click on columns->Select Columns). Look for a large number of GDI Objects to confirm the windows handle limit is indeed the problem.

Are you disposing the login form? You mention you have a-lot of controls, any way you can limit those, such as using a label and an array of text to display something instead of a bunch of labels or a grid of textboxes or the like.

Читайте также:  Уровень заряда батареи для windows 10

An example of a memory profiler you could use would be the .Net Memory Profiler.

(Update 3/30/16)

Revising the information you have provided me, three things have occurred to me:

Unregistering events

If you are dynamically creating and then removing Controls on your forms, you must ensure to unregister any event handlers from every event you have previously registered with this control. If you don’t, the event handler will hold a reference to the control and be prevented from being eligible for garbage collection (along with the GDI/USER objects), even if you call Dispose! They will remain held until you Dispose the parent Form.

Timer (and other, not-UI) events

Error Creating Window Handle (VB.NET)

I have a fairly large application written in VB.NET which seems to be suffering from a memory leak of one kind or another. Several times per day, I have instances of this application that crash (seemingly at random, but always after being used for almost a day). I’ve searched and read many forums and even questions asked here on Stack Overflow about this particular problem. What I’ve determined is that this is related to a memory leak and usually points to either the handles exceeding 10,000 or the objects exceeding the limit.

I’ve downloaded the memory pro filer and have used it to locate and fix several memory leaks in the program but that hasn’t seemed to slow down the daily crash count. My program uses a global error catcher to log these events and store information about them in the database. I’ve now got about 2 months worth of data but the error message doesn’t really help point me in any kind of direction. I’ve recently added the ability for this global error catcher to log the handles that the application has and so far it has been far below the 10,000 handle threshold. Usually it is under 1,000.

Long story short, my question is this. Is there some way to log the GDI object count so I can determine if that is causing my program to crash? Are there other ‘objects’ that might be causing the memory leak and crash besides these two and can I log those some how?

I’ve tried reading as much as I can and I just can’t get a good grasp on this so I appreciate any direction you can give me. It seems like these types of problems plague a lot of programs. Hopefully someone can help me and this can help others in the future.

A little more information about my program and environment. It mostly runs on Windows 7 64 bit machines (although some vista and XP machines are present), it is running on .NET 4.0 framework. The project consists of a few hundred forms, classes, and custom controls (built specifically for this project). I’m using .NET memory profiler 4.6 to check for memory leaks. I’ve run what I consider the most resource intensive operations on my computer for over an hour (opening and subsequently closing a lot of the screens, crunching gigs worth of data, etc. ) while watching the resources in the task manager (Handles, Threads, USER Objects, and GDI Objects) but none of them go over 1000.

Here is a copy of one of the logs from a crash event:

The only other though I had was that my global error catcher is crashing when it tries to load because it cannot create any more handles and I’m somehow losing that information. But the times when it isn’t crashing and it is able to log the handle count it is quite low (sub 1000). Is the garbage collector freeing up a lot of resources right after the crash before the program can log the high handle count? I’m just a little lost and confused about the data I have.

Оцените статью