C#: String as parameter to event?

前端 未结 4 1566
独厮守ぢ
独厮守ぢ 2021-01-04 17:22

I have a GUI-thread for my form and another thread that computes things.

The form has a richtTextBox. I want the worker-thread to pass strings to the form, so that e

4条回答
  •  死守一世寂寞
    2021-01-04 17:54

    Like this

    public class NewListEntryEventArgs : EventArgs
    {
        private readonly string test;
    
        public NewListEntryEventArgs(string test)
        {
            this.test = test;
        }
    
        public string Test
        {
            get { return this.test; }
        }
    }
    

    then you declare your class like this

    class MyClass
    {
        public delegate void NewListEntryEventHandler(
            object sender,
            NewListEntryEventArgs args);
    
        public event NewListEntryEventHandler NewListEntry;
    
        protected virtual void OnNewListEntry(string test)
        {
            if (NewListEntry != null)
            {
                NewListEntry(this, new NewListEntryEventArgs(test));
            }
        }
    }
    

    and in the subscribing Form

    private void btn_myClass_Click(object sender, EventArgs e)
    {
        MyClass myClass = new MyClass();
        myClass.NewListEntry += NewListEntryEventHandler;
        ...
    }
    
    private void NewListEntryEventHandler(
        object sender,
        NewListEntryEventArgs e)
    {
        if (richTextBox1.InvokeRequired)
        {
            this.Invoke((MethodInvoker)delegate
                {             
                    this.NewListEntryEventHandler(sender, e);
                });
            return;
        }
    
        richTextBox1.Text += e.Test;
    }
    

    I've taken the liberty of making the NewListEntryEventArgs class immutable, since that makes sense. I've also partially corrected your naming conventions, simplified and corrected where expedient.

提交回复
热议问题