Question

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.

Was it helpful?

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));
}

OTHER TIPS

Your code is correct, except for one tiny, yet very important, detail. You are subscribing to the event handler AFTER the code you expect to monitor is executed. Change your method NewScan to call StarScan after the event handler is registered:

private void NewScan(Object param) 
{ 
    Scan doScan = new Scan(); 
    doScan.Text += new Scan.TextHandler(SetText); 
    doScan.StarScan(Convert.ToInt32(checkBoxBulk.Checked)); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top