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:<
It's a runtime error, not a compiler error.
Your Form, "Main", has to be displayed (hence a window handle created) before you can make calls to BeginInvoke or Invoke on it.
What I usually do in these situations is leave it up to the Form to determine if it needs to use a call to BeginInvoke or Invoke. You can test that with a call to InvokeRequired (check MSDN).
So for starters, I'd get rid of the logAddDelegate call in the Loggin class's updateLog method. Just make a straight call to the form to add a log. Like so:
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private delegate void AddNewLogMessageEventHandler(string message);
public void AddLogMessage(string message)
{
object[] args = new object[1];
args[0] = message;
if (InvokeRequired)
BeginInvoke(new AddNewLogMessageEventHandler(AddLog), args);
else
Invoke(new AddNewLogMessageEventHandler(AddLog), args);
}
private void AddLog(string message)
{
this.Log.Items.Add(message);
}
}
}
So you can see, the Form itself is in charge of determining if it needs to call the method asynchronously or not.
However, this still won't fix your runtime error, because you're making a call to the form before its been displayed. You can check to see if the form's Handle is null or not, and that will at least allow you to verify whether or not you're dealing with a valid Form.