[英]Subscribe to event in dll from another application
我一直在尋找可能的解決方案,但似乎沒有一個與我真正需要的解決方案接近。 我有一個Windows窗體,可輸出到類庫(dll)。 我將此dll引用到控制台應用程序中,然后在dll中啟動GUI。 我希望能夠訂閱一個控制事件並在控制台應用程序中執行任何代碼。 當我想直接從控制台應用程序讀取或寫入dll中的屬性時,我沒有問題。 例:
MyDll.MyClass myObj = new MyDll.MyClass();
myObj.Textbox1.Text = "Hello World!";
但是,我想在dll中訂閱TextChanged事件,並將新文本輸出到控制台應用程序。 類似於以下內容:
public void textbox1_TextChaned(object sender, EventArgs e)
{
Console.WriteLine(myObj.textbox1.Text);
}
有什么辦法可以直接訂閱該事件? 還是其他事件?
將textbox1
的修飾符設置為public
訂閱TextChanged
事件:
myObj.Textbox1.TextChanged + = textbox1_TextChaned;
控制台應用程序中的以下代碼對我有用。 我指的是Windows窗體應用程序,而不是DLL,但我認為應該沒有太大區別:
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));
}
}
這不會直接回答您的問題,但是它將以更整潔的方式解決您的問題,IMO。
在控制台應用程序中:
IEventProcessor processor = new ConsoleEventProcessor();
MyDll.MyClass myObj = new MyDll.MyClass(processor);
然后以以下形式:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.