I have two WinForms applications and I need to add text to TextBox in Application1 from Application2. I’ve successfully done this using named pipes and WCF. I can successfuly call a method in Application1 from Application2 but I’m getting either “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.” error or the textbox is not updated at all.
Here’s my basic code. GetMessage is called by Application2. This one doesn’t update TextBox at all:
public void GetMessage(string msg)
{
UpdateTextbox(msg);
}
private void UpdateTextbox(string msg)
{
this.textBox1.Text += msg + Environment.NewLine;
}
This one throws Invoke error:
public void GetMessage(string msg)
{
Action a = () => UpdateTextbox(msg);
textBox1.BeginInvoke(a);
}
I tried to cheat my way by forcing creation of the handle with this, but it doesn’t update TextBox either:
public void GetMessage(string msg)
{
IntPtr handle = textBox1.Handle;
Action a = () => UpdateTextbox(msg);
textBox1.BeginInvoke(a);
}
What should I do?
Solved the problem thanks to this answer.
The problem is that the TextBox of the Form1 was on another instance of the Form1. Observe this code from
Application1.Form1which starts the named pipe service:If I am understanding it right, this starts an instance of
Form1. Thus, when Application2 callsApplication1.GetMessage, it callsServiceHost-instance-Form1.GetMessage.To access main instance of
Form1I changed my code to this:It works correctly now..