Question

I am getting the following runtime error message

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Here is what I think is going on. My winform constructor is creating some objects, one of which received asynchronous TCP/IP data. To make a long story short, I have event delegates which allow the class receiving the network data to call a routine from the Winform to print the data to a text box. This is so I can see what was received. I can see that data is immediately received. This happens before the winform constructor has finished.

I read around and you cannot invoke a winform or winform component until its handle has been created. I suspect this is what I am violating. Supposedly there is a function to force this. I tried adding the following code to my winform constructor to force the creation before I create my class receiving TCP/IP data. However, the error remains.

InitializeComponent();
this.CreateControl();
this.HistoryBox.CreateControl();

Here is the code for my winform delegate in case it helps:

    public void Print_Console_Message(string message)
    {
        Console_Output.Enqueue(message);
        this.Invoke(new EventHandler(PrintToConsole));
    }
    private void PrintToConsole(object sender, EventArgs e)
    {
        string message = Console_Output.Dequeue();

        if (message.Length != 0)
        {
            HistoryBox.AppendText(message + "\n" + "\n");
        }
    }

I realize there is a way to check object handle was created and avoid the call in that case, however, I am not interested in simply inhibiting some of the output.

Does anyone know how I can force the handle or control creation so that the delegate functions could be called before the constructor is finished?

Was it helpful?

Solution

According to the documentation you can do this by getting the .Handle property.

If the handle has not yet been created, referencing this property will force the handle to be created.

Alternatively, you could listen for the HandleCreated event and only Invoke after it's fired.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top