简体   繁体   中英

Subscribe to event in dll from another application

I've been looking all over for a possible solution, but none seem to come close to what I actually need. I have a windows form which outputs to a class library (dll). I reference this dll into a console application and then launch the GUI in the dll. I want to be able to subscribe to a control event and do what ever code in my console application. I have no problem when I want to read or write properties in the dll directly from my console app. Example:

MyDll.MyClass myObj = new MyDll.MyClass();
myObj.Textbox1.Text = "Hello World!";

However, I would like to subscribe to the TextChanged event in my dll and output the new text to my console app. Something along the lines of:

public void textbox1_TextChaned(object sender, EventArgs e)
{
    Console.WriteLine(myObj.textbox1.Text);
}

Is there any way to subscribe directly to that event? or some other event?

  1. Set the modifier of textbox1 to public

  2. Subscribe to the TextChanged event:

    myObj.Textbox1.TextChanged += textbox1_TextChaned;

The following code in a console app works for me. I'm referencing a Windows Form Application rather than a DLL, but I don't think there should be much difference:

 class Program
  {
    static WindowsFormsApplication1.Form1 frm;
    static void Main(string[] args)
    {
      frm = new WindowsFormsApplication1.Form1();
      frm.textBox1.TextChanged += textBox1_TextChanged;
      System.Windows.Forms.Application.Run(frm);

    }
    static void textBox1_TextChanged(object sender, EventArgs e)
    {
      Console.WriteLine((frm.textBox1.Text));
    }
  }

This doesn't answer your question directly, but it will solve your problem in a neater way, IMO.

  1. In your DLL define an interface (IEventProcessor).
  2. In your console application implement the interface (ConsoleEventProcessor).
  3. Pass an instance through the constructor of the form
  4. call its methods from the events in the form.

In the console app:

IEventProcessor processor = new ConsoleEventProcessor();    
MyDll.MyClass myObj = new MyDll.MyClass(processor);

Then in the form:

IEventProcessor _processor;
// constructor
public MyClass(IEventProcessor processor)
{
   _processor = processor;
}

public void textbox1_TextChaned(object sender, EventArgs e)
{ 
    // pass whatever parameters you need to use in the method
    _processor.ProcessText1Changed(textbox1.Text);
}

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