Wannabe
Wannabe

Reputation: 596

Add delegate to Windows Form

Problem: I want to write the same message to a textbox control that I am writing to a log file.

I have a windows form (Form1.cs) that calls a crosscutting class of static methods. In each of the crosscutting methods, they call WriteLogEntry to update a log file of what they are doing. I'd like to send back an event to Form1 so I can write the same log message to a control on the form.

I have looked at events but do not understand enough to make sense of the examples and have not found a simple enough example to do what I want. Can someone show me a simiple example of how to add an event to my code to accomplish this?

namespace MainForm
{
    public delegate void MyDel(string str);

    public partial class Form1 : Form
    {
        public event MyDel MyEvent;

        public Form1()
        {
            InitializeComponent();

            MyEvent += new MyDel(WriteSomething);

            Crosscutting.DoSomething();
        }

        public void WriteSomething(string message)
        {
            Console.WriteLine(message);
        }
    }

    //Crosscutting.cs

    public class Crosscutting
    {
        private static void WriteLogEntry(string message)
        {
             // Code to write message to log file.
        }

        public static void DoSomething()
        {
            WriteSomething obj = new WriteSomething();

            // Code to do something.

            WriteLogEntry("I'm doing something");
        }
    }
}

Upvotes: 0

Views: 1678

Answers (1)

Wannabe
Wannabe

Reputation: 596

After not being able to figure out how to use a delegate to get back to the form, I tried another way. By creating an instance of Form1 on "MyClass", I was able to use a public method to write back to the form. Not the way I wanted, but it is a way to get it done for now. If anyone can explain how to do this a better way, please do so.

public partial class Form1 : Form
{
    private string message = string.Empty;

    public static Form1 form;

    public Form1()
    {
        InitializeComponent();

        form = this;
    }

    public void UpdateTextBox(string message)
    {
        textBox1.Text += message + Environment.NewLine;

        this.Update();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var myClass = new MyClass();

        myClass.DoSomething();
    }
}


public class MyClass
{
    public void DoSomething()
    {
        Log("I did something");
    }

    private void Log(string message)
    {
        Console.WriteLine(message);

        Form1.form.UpdateTextBox(message);
    }
}

Upvotes: 1

Related Questions