Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to know that how to call event with delegate.
My code is

In file1.cs //this main file I have to go through using EacApi

C#
namespace Program1
   {
     private StatusEventHandler OnGetCamStatus;
     [ComSourceInterfaces("Program1.IEacApiEvents")]
     [ClassInterface(ClassInterfaceType.None)]
     [ComVisible(true)]
     [Guid("ED8211C0-50A6-4873-8964-31A381D96A23")]
     public class EacApi
     {
         public event StatusEventHandler OnGetStatus
       {
         [MethodImpl(MethodImplOptions.Synchronized)] add
         {
           this.OnGetStatus = this.OnGetStatus + value;
         }
         [MethodImpl(MethodImplOptions.Synchronized)] remove
         {
           this.OnGetStatus = this.OnGetStatus - value;
         }
       }
   }
   }


In file2.cs

C#
 namespace Program1
    {
      public delegate void StatusEventHandler(int iType, int iValue, int iDataSize, object data);
    }
In file3.cs

        namespace Program1
    {
      [ComVisible(true)]
      [Guid("5D3FB90D-E41F-4412-B3D4-D6B7939E5214")]
      [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
      public interface IEacApiEvents
      {
        [DispId(3)]
        void OnGetCamStatus(int iType, int iValue, int iDataSize, object vData);
        }
        }
Posted
Updated 31-May-13 2:12am
v2

1 solution

There is no such thing as "call a delegate". A delegate instance is invoked, which is a very different things: all the handlers from its invocation list get called. This is done like this:
C#
if (OnGetStatus != null)
    OnGetStatus.Invoke(this, new StatusEventArgs(/*...*/)); // or whatever is required by the signature of StatusEvenHandler

You can invoke this event only in this class (declared class), nowhere else, which is an important fool-proof feature.

Here, I made up the type StatusEvenArgs assuming that you are using the common event declaration pattern:
C#
class StatusEventArgs : System.EventArgs { /* ... specific event args parameters are defined in this class */ }

//...

public class EacApi {
   public event System.EventHandler<StatusEventArgs> OnGetStatus;
   //...
}


If you are doing something else, resort to this pattern. If, by some reason, you want to invoke event somehow else you should… review your code design; it's now going to happen. If this is the case, better explain your ultimate goal, they I would, most likely, be able to suggest a solution.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900