0

ここでの最後の質問からいくつかの進歩がありました:マルチスレッドクラスからWindowsActiveFormへのイベントテキストのポストバック

私もこれでいくらかの進歩を遂げました:http://www.codeproject.com/KB/cs/simplesteventexample.aspx

しかし、私は再び立ち往生しています。コードがイベントをトリガーしたり、適切に処理したりしていないようです(私はカスタムイベントに本当に慣れていません)。

これが私が現在コードに関して持っているものです。

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...
}

私のWindowsフォーム:

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

繰り返しになりますが、エラーは表示されませんが、テキストボックスはまったく更新されていません。私は何かを書いているのではないと確信しています。カスタムイベントのトピックについては十分に無知です。これを修正する方法がわかりません。

4

2 に答える 2

1

コードを実行するに、イベントをサブスクライブする必要があります。

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));
}
于 2011-10-25T21:05:52.860 に答える
1

あなたのコードは正しいですが、1つの小さな、しかし非常に重要な詳細を除いて。監視する予定のコードが実行された後、イベントハンドラーにサブスクライブしています。イベントハンドラが登録された後NewScanに呼び出すようにメソッドを変更します。StarScan

private void NewScan(Object param) 
{ 
    Scan doScan = new Scan(); 
    doScan.Text += new Scan.TextHandler(SetText); 
    doScan.StarScan(Convert.ToInt32(checkBoxBulk.Checked)); 
}
于 2011-10-25T21:11:33.473 に答える