This question already has answers here:
"Error Creating Window Handle"
(11 answers)
Closed 10 years ago.
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.
System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e)
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.
Good Luck!
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.)
I think it's normally related to the computer running out of memory so it's not able to create any more window handles. Normally windows starts to show some strange behavior at this point as well.
I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory.
I just commented controls.clear() method and include few lines of code to dispose the controls.
Something like this
for each ctl as control in controlcollection
ctl.dispose()
Next
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.
In C# it seems that if a control e.g. a Panel is programmatically reassigned from, say, a Form to a Tab Page by changing the Panel.Parent property, calling Dispose() on the Form won't dispose the Panel, neither will calling Controls.Clear() on the Tab Page. Even a direct call Panel.Dispose() won't actually dispose it, unless its Parent is manually set to null beforehand.
I added a check that makes it work...
if (_form.Handle.ToInt32() > 0)
{
_form.Invoke(method, args);
}
it is always true, but the form throws an error without it.
BTW, my handle is around 4.9 million
Definitely too many handles(memory leak issue):
IT Jungles: System.ComponentModel.Win32Exception: Error creating window handle
The out of memory suggestion doesn't seem like a bad lead.
What is your program doing that it gets this error?
Is it creating a great many windows or controls?
Does it create them programatically as opposed to at design time?
If so, do you do this in a loop? Is that loop infinite?
Are you consuming staggering boatloads of memory in some other way?
What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.
Related
I am a fairly experienced WinForms developer. I have an MdiApplication that used to work well. However, recently the main shell of the application, for which we use ComponentOne RibbonForm, has been updated in a big way. This update did affect some of our other 3rd party components, which we established was due to ComponentOne's use of DoEvents() in their event code. I thought I had cleaned up all of the code causing problems but I now have found another...
When I have multiple MdiChildren open and select one of these in code from an button click event on the ribbon form via
document.Activate();
document.EditorControl.Select();
document.EditorControl.Focus();
the other open MdiChildren documents still have focus, that it the forms are highlighted and input is not set on the document I set in code. Two questions:
How can I ensure that the Form I want to make active is the only one that is active?
Linking to the above; setting one form as active using form.Activate() should deactivate the others MdiChildren, but it is not - how can I deactivate the other windows in code?
Thanks for your time.
[Too long for a comment]
I am sick to the hind teeth with fighting C1. Esp. the Ribbon. I have confirmed with their support that they do use DoEvents() which they use to yield on their Gui threads. I am now going to switch to DevExpress which should be straight forward for my MVC application...
C1's use of DoEvents() messes up the normal flow of your application. DoEvents() is asynchronous which means it terminates before the application has actually processed any outstanding events, so if you're using it in a procedure with many sequential statements, calling DoEvents() causes a huge disturbance whenever it's called. This is what I think we are seeing when we perform our MDI operations, but we can never be sure without the C1 source code.
I hope this helps.
With a Winforms .net application, we have an issue where an image list occasionally becomes corrupted.
By corrupted I mean that the count of the number of images will be wrong and/or the images may have been replaced by system images (like dialog box icons).
For example, the screenshot below shows the imageInfoCollection showing the correct number, but the count showing the incorrect number.
The image list is on a form that is opened repeatedly by the user throughout the use of the application. The image list is used by a tab control on the form.
The issue occurs only occasionally, anywhere between every 5 and 20 times of opening the form.
The code to load the imagelist is built by the designer, and uses images from the resources:
this.imageListCallTakingScreen.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListCallTakingScreen.ImageStream")));
this.imageListCallTakingScreen.TransparentColor = System.Drawing.Color.Transparent;
this.imageListCallTakingScreen.Images.SetKeyName(0, "spinner.png");
this.imageListCallTakingScreen.Images.SetKeyName(1, "recommendation-star.png");
this.imageListCallTakingScreen.Images.SetKeyName(2, "recommendation-star_red.png");
this.imageListCallTakingScreen.Images.SetKeyName(3, "recommendation-star - Transparent.png");
this.imageListCallTakingScreen.Images.SetKeyName(4, "Initialisation_fail16.png");
this.imageListCallTakingScreen.Images.SetKeyName(5, "information_white.png");
this.imageListCallTakingScreen.Images.SetKeyName(6, "Check-icon.png");
The imagelist isn't used anywhere other than in the designer.cs code to create it and wire it up to the tab control (except for the error trapping line I have put in):
Ideas? We are stuck on this one and google doesn't turn much up.
The imageInfoCollection field properly tracks the number of images you have in the ImageList. The Count property tracks the number of images that are actually present in the native Windows imagelist control.
There's only one way those values could have a mismatch that I can think of. Your program is leaking GDI object handles. A fairly common problem in Winform apps. That works for quite a while until you reach the operating system quota for such handles, after you've consumed 10,000 of them then Windows stops allowing you to create more. The error checking in the .NET wrapper class is not entirely kosher so this can happen without an exception getting generated. You'll see some more strange painting artifacts when you hit that limit btw.
You can get a basic diagnostic from Task Manager, Processes tab. Use View + Select columns and tick GDI Objects and USER objects. Observe these values while you operate the program like a user would. A steadily climbing value for GDI Objects spells doom. A hint that you are forgetting to use the using statement to dispose System.Drawing objects. And the garbage collector not running often enough to keep you out of trouble. You need to fix this in your code so the counter remains stable at, say, no more than several hundred objects.
A steadily climbing value for USER Objects is also a very common Winforms bug. That's a pretty fatal one, it will jack-up the GDI object count as well and the GC cannot fix this problem. This will happen when you remove controls in your code with Controls.Remove/At() or Controls.Clear() and forget to dispose the removed control objects.
I am developing an extension for existing application via COM.
Current interface of the application to extend allows to create custom property windows and use them inside that application.
Now, I am using .NET for that purpose and have strange problems:
extensionForm = new Form();
extensionForm.SetBounds(0, 0, 100, 100);
extensionForm.Controls.Add(new Button());
ExApplAPI.AddCustomPropertyWindow(extensionForm.Handle.ToInt32(), "Ololo");
As you can see below, the property sheets actually get extended, but after that something strange starts to happen.
Basically, if I switch to Ololo tab, then back to any of other 3 tabs (Attributes, Drawing or Services), the application freezes. I also know that the freeze happens inside of some unmanaged code block.
Another interesting fact here is that if I don't write the extensionForm.Controls.Add(new Button()) (with or without the Suspend / Resume Layout calls), everything works fine. So, if the recently constructed form has no controls (buttons or any other) on it, it doesn't freeze.
Here is a Spy++ log on the Ololo window right before the freeze (last message is the WM_CTLCOLORBTN, right after that the application became frozen):
Combining everything together:
Freezing happens only if I switch from Ololo to some other tab and then switch to the Ololo tab again.
Freezing only happens if the integrated form has at least one control on it, forms without controls don't freeze.
Application is not running any managed code at the moment and is not spending any CPU time.
So - any ideas / similiar problems solved / etc to help me in this case?
The Win32 HWND handles for the Forms in .NET are lazy initialized.
And I think this may be a problem here.
You may argue that the handle is created in your line ExApplAPI.AddCustomPropertyWindow(extensionForm.Handle.ToInt32(), "Ololo"); due to accessing Handle property.
It is true and what documentation acknowledges.
However, it creates the handle for the Form itself, but handles for child controls (Button in this case) are not created. This can be forced by calling CreateControl method. See more documentation.
I don't know if not having a handle for button may be a cause of your problem, but this is definitely something I would investigate.
To summarize, I suggest changing your code to:
extensionForm = new Form();
extensionForm.SetBounds(0, 0, 100, 100);
extensionForm.Controls.Add(new Button());
extensionForm.CreateControl();
ExApplAPI.AddCustomPropertyWindow(extensionForm.Handle.ToInt32(), "Ololo");
Are there any exception thrown?
We had an similar behavior when using WPF and COM, it solved by calling reset double calculation by using
[DllImport("msvcr70.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int _fpreset();
It is possible that the resource handle is not right. As you mentioned this happens only when the integrated form has atleast one control in it, Ololo tab is not able to find it's resources when active again. Please try storing resource handle the first time and then restoring it everytime the tab is active.
To understand why the application hangs, there are 2 things that may help:
Can you post a stack trace of the UI thread while the application is hung?
Which thread calls your code and actually creates the windows?
I'm experiencing a annoying issue in my .NET Windows Forms application.
I have a MainForm (A) and a progress form (B) that is shown modal when I start a long operation.
When the operation finishes, and B is closed, it seems that the window that is behind my application (is occurs usually with Skype) is brought to front during few milliseconds and, then my application is activated normally.
Is only a small flickering, but annoying. Here I write some tips that could help to find the solution:
I called showDialog without IWin32Window, but I added it without success result.
I closed B using Close(), then I tried Hide() and then Close() but did not help.
The code that executes the ShowDialog() is invoked from the UI thread, so it don't seem to be a threading issue.
Any clue would be appreciated. Thanks in advance.
I was experiencing these same symptoms and it was driving me crazy.
I finally discovered the problem was that i was calling this.Dispose() instead of this.Close() to close the modal window I'm not sure why I called this.Dispose() in the first place.
After switching methods, the problem went away.
I realize that this thread is old and this is not the cause of your problem, i am just trying to help anyone else who made the same mistake that I did.
Check if you DON'T call Hide or Close. The only way to avoid flickering is DialogResult.
Upd:
this.DialogResult = DialogResult.Ok
Check handlers OnFormClosing and etc. They might containt wrong method call.
The little trick is to set Owner explicitly
_dialog.Owner = this;
_dialog.ShowDialog();
People who are editing the post - _dialog.ShowDialog(this) works a bit different.
Look at owner = ((Control) owner).TopLevelControlInternal; in decompiled code
Edited by someone:
Or...
_dialog.ShowDialog(this);
These calls are identical according to MSDN
Do not call Close for modal window (it will not be disposed and memory leak is guaranteed)
Set this.DialogResult = DialogResult.OK
Call Dispose() from the parent, NEVER from the form you are closing
Remember of disposing all of your components holding by the form IContainer in Dispose(bool) (VS Designer implementation of Dispose(bool) is usually not enough not to have memory leaks)
In my case I was also facing the same issue in my VB.Net winform application but a bit different scenario.
I was having a user control which opens up a dialog using showdialog() say dialog1 and on filling some data it hides dialog1 and opens up dialog2 using showdialog() again.
In the process of hiding dialog1 and showing dialog2 flickering occurs and it shows the window at background for a moment.
After trying so many solutions and workarounds none work for me. I found one workaround myself which might help others.
To hide dialog1 I was using Me.Hide(), The solution is to change the opacity of form instead of calling Hide() method.
'Me.Hide()
Me.Opacity = 0
After this workaround the application works fine without any flickering issue.
PS: The above code lines are in VB.Net but enough for a .Net winform application developer to get the idea for fixing this issue.
Okay,
it sounds like
In the main window a user starts a long operation
You display a progress modal window
Operation completes you close the progress window
Your main window doesn't display immediately. Instead something behind it shows through for a second or less.
Your main window completes it's redraw operation and is 100% visible.
This happens more often when you have applications such as Skype running.
If that's the case there are many different possible causes. For example, your video drivers might have a bug in them causing delays in off screen compositing under certain conditions.
The system itself might even be experiencing a blocking CPU operation at the moment. This is something that could be caused by the time it takes your code to close the dialog and go back to the main form. You might look to see if there is anything else you are doing between the time the progress closes and you return UI control back to the user.
The system might simply be memory constrained and your operation causes a huge swap to disk. When the operation completes, windows might be notified that it needs to pull previously swapped memory from disk and shove it back into RAM, causing a delay.
I'd run the app with Nothing else loaded but task manager or resource monitor and see what happens. If the problem no longer occurs, then look into adding more RAM to your machine and/or ignore it.
If it's still occuring, and your memory usage leaves nearly nothing left then, again, add RAM or ignore.
If it's still occuring but memory usage is low, investigate your code to see what you are doing between the closing of the dialog and release of control of the main window back to the user.
You could try double buffering your form with this example:
Tends to eliminate flicker on screen updates.
I'm getting this nasty 'error creating window handle' during the startup itself i.e the login form. I would have looked into the optimizing the controls if it would have come after the UI is up. This is coming during the load of first form which basically has only login & password textbox controls.
The program is C# winforms.
I probably need more information but my guess is that you have a memory leak somewhere in your program. Try running Task Manager to see if you have a thread or handle growing massive.
If you do, you probably need to dispose some UI elements somewhere in your code.