Modify visual element by another thread

Asked

Viewed 589 times

7

I want to define by a Thread the content in a Richtextbox but I get an error saying

Cannot make calls from another thread distinguished from the same Textbox


I have heard that it is possible to use the option Control.Invoke I was very much in doubt at that point.

In short, I want to develop an APP that without starting CMD with the window, follow commands and can send commands to CMD, I already have the code ready but at the time I configure RedirectStandardOutput=true ends up only when the process closes it shows the log.

That’s why I’d like to implement a Thread on top of the textbox to with no need to close the process and show the "log".

1 answer

6


Since you haven’t shown the code of what you’re trying to do, I’ll give a more general answer.

You can do it

this.Invoke(new MethodInvoker(() => textBox.Text = "NovoTexto"));

I would do a function to change the value of TextBox, where in the function itself would check whether to use the Invoke or not. It’s more a matter of taste. If you’re interested, it would look that way.

public void SetText(TextBox txtbox, string texto) 
{
    if (txtbox.InvokeRequired)
        txtbox.Invoke(new MethodInvoker(() => txtbox.Text = texto));
    else
        txtbox.Text = texto;        
}

Use

SetText(textBox, "Novo Texto");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.