2013-07-03 3 views
0

사용자가 로그인하지 않고 두 가지 맞춤 이벤트에 문제가 발생했습니다. 예외가 발생하지 않으며 컴파일러 오류도 발생하지 않지만 애플리케이션을 실행할 때 콘솔에 글을 쓰지 않아도됩니다. 이벤트가 전혀 발사되지 않습니다! 나는 사건이 일어 났을 때 메시지를 보여달라고 말했지만, 아무 것도 일어나지 않는다. 나는 그것이 나의 의심을 확인한다고 믿는다.내 맞춤 이벤트가 실행되지 않는 이유는 무엇입니까?

나는 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); 
     } 
     } 
+0

OnActive (EventArgs e) 메서드는 OnInactive (EventArgs e) 메서드에서 복사 붙여 넣은 것 같습니다. 정말로 동일한 두 가지 방법이 필요하거나 오타가 있습니까? –

답변

5
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; 
+1

나는 이것을 쓰려고했다! 그는 보호 된 가상 공법을 놓치고있었습니다. 좋은 대답. 여기에 마이크로 소프트의 예제가 있습니다 : http://msdn.microsoft.com/en-us/library/9aackb16.aspx – Andres

+0

어떻게 이벤트를 처리합니까? =] 좋은 대답 btw 주셔서 감사합니다! –

+0

더 명확하게하기 위해 답을 편집했습니다. 기본적으로 이벤트 핸들러 메서드는 이미 괜찮 았습니다. 이벤트가 발생할 때 호출되도록 제대로 등록해야합니다. –

관련 문제