简体   繁体   中英

C# EventHandler : How to handle EventHandler in client application?

I have written a class library(dll) which handle Telephony calls. This class library has delegates that handle phone call events such as OnCallReceived, OnHoldCall etc.

So now i want to add this class library to my Windows Forms App, and be able to handle Phone Call events(OnCall, OnHolde etc) in my Windows Forms application. How can achieve this?

For example

//My Class Library

Class Test
{
   ThirdParyLibrary tpl

   public Test()
   {
      tpl= new tpl();
      tpl.OnReceiveCall += Handler(OnReceiveCall);     
   }

   public void OnReceiveCall()
   {
      //i want this event to take place in client app
   }  
}

//My Windows Forms App

Client App

public main()
{
   Test t =new Test()
   //i want OnReceiveCall to be processed here
   //t.OnReceiveCall
   {
      Message.Show('You received a call');
   }
}

// i want this event to take place in client app

Since you want the Event Handling mechanism to take place in the Client App, which I suppose is another Class containing Main , I have created a small console that replicates the problem scenario


Uploaded to fiddle as well

using System;

namespace Test
{
    public class ThirdPartyLibrary
    {
        public delegate void dEeventRaiser();
        public event dEeventRaiser OnReceiveCall;
        public string IncomingCall(int x)
        {

            if (x > 0 && OnReceiveCall != null)
            { OnReceiveCall(); return "Valid "+x.ToString(); }
            return "Invalid"+x.ToString();
        }
    }



    public class EventSubscription
    {

        public EventSubscription()
        {
            ThirdPartyLibrary a = new ThirdPartyLibrary();
            a.OnReceiveCall += HandleTheCall;
            var iAnswer = a.IncomingCall(24198724);
            Console.WriteLine("Call received from "+iAnswer);
        }

        public virtual void HandleTheCall()
        {
            Console.WriteLine("Default way I handle the call");
        }

    }

    public class Program : EventSubscription
    {
        public override void HandleTheCall()
        {
            Console.WriteLine("Override sucessful, new way to handle the call ");
        }

       static void Main(string [] args)
        {

          Program pb = new Program();  // Control goes EnventSubscription constructor as it is derived 
            Console.Read();
        }

    }
}

Output :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM