How to reach RichTextbox1 from a static method?

Bradley Rogers 116 Reputation points
2021-06-23T15:35:17.567+00:00

vs2019 Windows Form app (not web) there is the Serial IO and its event handler that uses a delegate,
public static void DataReceivedHandler(object sender, SerialDateReceivedEventArgs e) {

serialport sp = (SerialPort)sender;
read, put into string, etc...

}

HOW to get that data into RichTextBox1 ? or if not possible how to even use that data? Since its static it wont see the form. anything Ive tried gets a RUNTIME error saying cross thread something or other. trying to modify RichTextBox1 from a thread that didnt create it. Sorry, you lose!

whats the solution? use of Assembly? Win32 calls making the handler from scratch?

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,823 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,589 questions
{count} votes

Accepted answer
  1. Bradley Rogers 116 Reputation points
    2021-06-23T17:10:02.447+00:00

    Thanks, well that got it closer, found the answer to be:

      private delegate void AppendTextDelegate(string text, RichTextBox rtb);
    
            private void AppendText(string text, RichTextBox rtb)
            {
                if (rtb.InvokeRequired)
                {
                    rtb.Invoke(new AppendTextDelegate(AppendText), text, rtb);
                }
                else
                {
                    rtb.AppendText(text + Environment.NewLine);
                }
            }
    

2 additional answers

Sort by: Most helpful
  1. Viorel 112K Reputation points
    2021-06-23T17:04:11.717+00:00

    If the "cross-thread" issue is the only problem, then replace the statements like richTextBox1.Text = "some text" with:

    richTextBox1.Invoke( new Action( ( ) => richTextBox1.Text = "some text" ) );

    1 person found this answer helpful.
    0 comments No comments

  2. Bradley Rogers 116 Reputation points
    2021-06-23T20:22:57.553+00:00

    richTextBox1.Invoke( new Action( ( ) => richTextBox1.Text = "some text" ) );

    compiler says "Action"? not known unless I missed something else Action was not defined, not found

    0 comments No comments