Wednesday, April 14, 2010

Value Close() cannot be called while doing CreateHandle()

The error Value Close() cannot be called while doing CreateHandle() usually happens when we try to close the form in the constructor or Load event.

For example,

the following code gives the error:


Private Sub RootForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



'Some Validation
'If Failed then close the form
Me.Close 'The exception throws -->Value Close() cannot be called while doing CreateHandle()
End Sub

Solution:
The form should not be closed on load event. Instead we can write the procedure to close the form, and call the procedure in button click.

But the form cannot be closed during the loading point of time. So the form's closing call should be done after loading the form.

7 comments:

  1. But I have to close During Load

    ReplyDelete
  2. this.BeginInvoke(new MethodInvoker(Close));

    ReplyDelete
  3. It works!
    I moved the Close() from the Constructor of the Form to the OnShown event.
    Thank you!

    ReplyDelete
  4. thanks for this article

    ReplyDelete
  5. I found same problem when i use form X button on forms right hand corner.
    "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

    Additional information: Value Dispose() cannot be called while doing CreateHandle().
    "
    I try this solution and it works
    I found form property Cancel Button which assign as 'None'
    I add new exit button and do exitbutton click event In that i call function as
    'Close();'
    this exitbuttotn i link to 'form property Cancel Button'
    It works well when i click on form X button.
    I change that and assign new procesdure which has

    ReplyDelete