Search code examples
c#.netwinformseventscustom-event

Custom Events in C#


I have made some progress from my last question here: Event Text Postback from Multithreaded Class to Windows ActiveForm

I also made some progress with this: http://www.codeproject.com/KB/cs/simplesteventexample.aspx

But I am stuck again, the code doesn't seem to be triggering the event or properly handling it (I am really new to custom events).

Here is what I currently have code wise.

public class TextArgs : EventArgs
{
    private string CurrentText;

    public string Text
    {
        set
        {
            CurrentText = value;
        }
        get
        {
            return this.CurrentText;
        }
    }
}

class Scan
{
    public event TextHandler Text;
    public delegate void TextHandler(Scan s, TextArgs e);

    private void ProcessDirectory(String targetDirectory, DateTime cs)
    {
        SetScanHistory(targetDirectory);

        // Does a bunch of stuff...
    }

    // EDIT: Forgot this bit of code; thanks for pointing this out :)
    // Sets the text of scan history in the ui
    private void SetScanHistory(string text)
    {
        if (Text != null)
        {
            TextArgs TH = new TextArgs();
            TH.Text = text;
            Text(this, TH);
        }
    }

    // Does more stuff...
}

My Windows Form:

public partial class MyWinForm: Form
{
    private void NewScan(Object param)
    {
        Scan doScan = new Scan();
        doScan.StarScan(Convert.ToInt32(checkBoxBulk.Checked));
        doScan.Text += new Scan.TextHandler(SetText);
    }

    // Sets the text of txtScanHistory to the text 
    private void SetText(Scan s, TextArgs e)
    {
        // Invoke is always required (which is intended)
        this.Invoke((MethodInvoker)delegate
        {
            txtScanHistory.Text += e.Text + Environment.NewLine;
        });
    }
}

So again, I am not seeing any errors, but the textbox is not updating at all. I am sure I am not doing something write, I am just ignorant enough on the topic of custom events I am not sure how to fix this.


Solution

  • You need to subscribe to the event before running the code:

    private void NewScan(Object param)
    {
        Scan doScan = new Scan();
        // Change the order so you subscribe first!
        doScan.Text += new Scan.TextHandler(SetText);
        doScan.StarScan(Convert.ToInt32(checkBoxBulk.Checked));
    }