Search code examples
c#winformstelerik

Redirect output to another form


I have a WinForms application with two forms - Form1 and Form2. I have a loop in Form1 that sends emails. I would like to send the status messages from the loop in Form1 to a RichTextBox in Form2. How can I accomplish this? Any feedback is appreciated.


Solution

  • The solution depends on the relation between the two forms: does Form1 know about Form2, for instance because Form1 created Form2?

    class Form1 : Form
    {
        private Form2 Form2 {get; set;}
    
        private void CreateForm2()
        {
            this.Form2 = new Form2;
        }
    
        private void SendStatusMessage(StatusMessage message)
        {
            this.Form2.ProcessStatusMessage(message);
        }
    }
    

    If Form1 does not know about Form2, but Form2 knows about Form1, then you should change Form1 such, that it sends events whenever a Status message is available.

    public class EventStatusMessageArgs : EventArgs
    {
        public StatusMessage Message { get; set; }
    
    }
    
    class Form1 : Form
    {
        public Event EventHandler<EventStatusMessageArgs> StatusMessageCreated;
    
        protected virtual void OnStatusMessageCreated(StatusMessage statusMessage)
        {
             var eventHandler = new EventStatusMessageArgs
             {
                  SatusMessage = statusMessage;
             };
             this.StatusMessageCreated?.Invoke(this, eventHandler);
        }
    
        private void CreateStatusMessage(...)
        {
            StatusMessage statusMessage = ...
            this.OnStatusMessageCreated(statusMessage);
        }
    }
    
    class Form2 : Form
    {
        // Form2 somehow knows about existence Form1
        public Form1 Form1 {get; set;}
    
        public void OnFormLoading (object sender, ...)
        {
             // subscribe to events from Form1:
             this.Form1.StatusMessageCreated += this.OnForm1CreatedStatusMessage;
        }
    
        public void OnForm1CreatedStatusMessage(object sender, EventStatusMessageArgs args)
        {
             StatusMessage createdStatusMessage = args.StatusMessage;
             this.ProcessCreatedStatusMessage(createdStatusMessage);
        }
    }
    

    Third scenario: Form1 and Form2 don't know about each others existence. Luckily mainForm who created Form1 and Form2 does:

    class MainForm : Form
    {
        private readonly Form1 form1;
        private readonly Form2 form2;
    
        public MainForm()
        {
            InitializeComponents();
    
            this.form1 = new Form1() {...};
            this.form2 = new Form2() {...};
    
            // make sure that the StatusMessage events from form1 go to form2:
            this.form1.StatusMessageCreated += this.form2.OnForm1CreatedStatusMessage;
        }           
    }
    

    By the way: always unsubscribe from the events when the item is Disposed.