简体   繁体   中英

Can't write to the richTextBox

I have this simple program :

private static System.Timers.Timer t3;

    private void button1_Click(object sender, EventArgs e)
    {
        t3 = new System.Timers.Timer(5000);
        t3.AutoReset = true; t3.Enabled = true; t3.Elapsed += OnTimedEvent3;

    }

    private void OnTimedEvent3(Object source, ElapsedEventArgs e)
    {
        // MessageBox.Show("event raised");
        richTextBox1.Text = "t3 is elapsed ";// 
      }

PROBLEM : : Nothing appears in the richTextBox1 after event is fired ! I have tried MessageBox and that works fine . what could be the problem ??

Your problem is the following: The eventhandler of your timer is running on a different thread like your UI. You need to invoke the control like

if(richTextBox1.InvokeRequired == true)
{
    richTextBox1.Invoke((MethodInvoker)delegate
    {
      richTextBox1.Text = "t3 is elapsed "
    });
}
else
{
    richTextBox1.Text = "t3 is elapsed ";
}

to access it correctly. Thats because UI objects are related to their thread. Creating a MessageBox for example is possible out of every thread - because your Box is not existing already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM