簡體   English   中英

為什么我的自定義事件未觸發?

[英]Why isn't my custom event firing?

我正在制作一個用於記錄用戶不活動狀態的應用程序,並且遇到了一些自定義事件的問題,沒有引發異常,也沒有出現編譯器錯誤,但是當我運行我的應用程序時,沒有任何內容寫入控制台,這使我覺得該事件根本沒有開火! 我已經告訴活動如果彈出消息則顯示一條消息,但是什么也沒有發生,我相信這證實了我的懷疑。

我不是C#或自定義事件的專家,因此將不勝感激任何幫助=]

我的自定義事件代碼如下:

             Inactivity inact = new Inactivity();
             inact.Active += inactivity_Active;
            inact.Inactive += inactivity_Inactive;

     public void inactivity_Inactive(object sender, EventArgs e)
            {

            var logdata1=Inactivity.GetIdleTime();
            System.Diagnostics.Debug.WriteLine(logdata1);
            MessageBox.Show("Inactive");
        }

        public void inactivity_Active(object sender, EventArgs e)
        {

            var logdata2 = Inactivity.GetIdleTime();
            System.Diagnostics.Debug.WriteLine(logdata2);
            MessageBox.Show("Active");
        }

這些是將引發活動事件和非活動事件的方法

    public void OnInactive(EventArgs e)
    {
        EventHandler inactiveEvent = this.Inactive;
        if(inactiveEvent!=null)
        {
            inactiveEvent(this, e);
        }
    }


   public void OnActive(EventArgs e)
   {

       EventHandler inactiveEvent = this.Inactive;
       if (inactiveEvent != null)
       {
           inactiveEvent(this, e);
       }
       }
Inactivity inact = new Inactivity();

這不是您定義事件的方式。 您可以這樣定義一個事件:

public event EventHandler<EventArgs> Active;
public event EventHandler<EventArgs> Inactive;

然后通過編寫/調用以下方法引發這些事件:

protected virtual void OnActive(EventArgs e)
{
    EventHandler<EventArgs> active = Active;
    if (active != null)
    {
        active(this, e);
    }
}

protected virtual void OnInactive(EventArgs e)
{
    EventHandler<EventArgs> inactive = Inactive;
    if (inactive != null)
    {
        inactive(this, e);
    }
}

您的事件處理程序方法正確。 作為參考,我在這里重復了它們:

public void inactivity_Inactive(object sender, EventArgs e)
{
    var logdata1=Inactivity.GetIdleTime();
    System.Diagnostics.Debug.WriteLine(logdata1);
    MessageBox.Show("Inactive");
}

public void inactivity_Active(object sender, EventArgs e)
{
    var logdata2 = Inactivity.GetIdleTime();
    System.Diagnostics.Debug.WriteLine(logdata2);
    MessageBox.Show("Active");
}

您將在此代碼引發相應事件時注冊要調用的那些代碼,例如,您可以將其放入該類的構造函數中。

Active += inactivity_Active;
Inactive += inactivity_Inactive;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM