I just posted a question about how to get a delegate to update a textbox on another form. Just when I thought I had the answer using Invoke...this happens. Here is my code:<
This is to help in case any other person got caught up with this. My problem: VB.net: “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.” I closed a form which has a handler for the event am calling to update the delegate, without removing the handler for the event.
What I did: When I close the form, I removed all the handlers, and assigned them back when i opened the form. It solved the problem.
That error tends to happen if you invoke on a window that has not yet been 'shown'. Are you sure you're not creating a second instance of the main class with your code in the Logging class (specifically, the first line)? It may be that the main form you are calling log on is NOT the main form you are looking at. If you want to check, add a call to "MainClass.Show()" just inside your logging call. If you get a second copy of the main form popping up, then the problem is that your logging class is not referencing the right 'instance' of your form.
Think of the class as a 'blueprint'. Each instance of the class (created with the word 'new') is another object, created from the blueprint. Just because two objects (in this case, your two main forms) share the same blueprint, doesn't mean that you can use them interchangeably. In this case, you already have a main form, and you want to 're-use' it. You can try:
MainClass myMainForm = Application.OpenForms.OfType<MainClass>().First();
logAddDelegate = myMainForm.logAdd;
logAddDelegate(message);
inside your log function instead of what you currently have. The difference is that the call to Application.OpenForms.OfType().First will go into your application, and retrieve the ACTUAL main form that you are seeing (technically, it will retrieve the first instance of it) and make your invocation on that form, directly.
Hope this helps.
Is this your exact code? You are calling this.Log.Items.Add(message);
in your add(string) method, but your logging class is called Logging, not Log. Have you got another form called Log perhaps? If that form hasn't been created when you call the add method, you will get this exception.