User Tools

Site Tools

blog:2020-05-12_c_access_form_components_from_thread



2020-05-12 C#: Access Form Components from Thread

  • I have a WinForms application, that launches a function to access WinForm RichTextBox in a different thread (from another class).
  • We can easily access RichTextBox from main form thread but, if I access it from a thread, it throws an error which says that I'm trying to access the component from another thread.

Our Solution

  • Since the RichTextBox control is owned by the thread that creates it. In the case, the thread that we start owns the form because it paints it so it is going to be the forms UI thread.
  • when we try to use another thread to make changes to the control, it will throw an exception just like previously said. The way around this is to invoke the thread that created it to come and make the change that like this:
    richTextBox1.BeginInvoke(new Action(()=>
    {
      // Do our control for the RichTextBox codes here.
    }));
  • Examples:

TAGS

  • 242 person(s) visited this page until now.

Permalink blog/2020-05-12_c_access_form_components_from_thread.txt · Last modified: 2020/05/12 11:16 by jethro

oeffentlich