我有两种形式,我试图捕获从frmEventReceive.cs中的frmEventGenerate.cs生成的事件。
在这个例子中,我可以从frmEventGenerate.cs接收事件,但不知道如何在frmEventReceive.cs中捕获它? frmEventReceive.cs是我创建frmEventGenerate.cs的启动表单。
有人能指出我正确的方向,我想我是愚蠢的!
谢谢
frmEventGenerate.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Events
{
public delegate void LinkToEventHandler();
public partial class frmEventGenerate : Form
{
public static event LinkToEventHandler Evt;
public frmEventGenerate()
{
InitializeComponent();
Evt += new LinkToEventHandler(ReceiveEvent);
SendEvent();
}
public static void SendEvent()
{
if (Evt != null)
{
Evt();
}
}
public void ReceiveEvent()
{
System.Console.WriteLine("Received Event - This works ok");
}
}
}
frmEventReceive.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Events
{
public partial class frmEventReceive : Form
{
public frmEventReceive()
{
InitializeComponent();
frmEventGenerate frmGen = new frmEventGenerate();
}
public void ReceiveEvent()
{
System.Console.WriteLine("I want to be able to receive the even here!");
}
}
}
答案 0 :(得分:3)
在构造函数中,在实例化frmEventGenerate
之后:
frmGen.Evt += ReceiveEvent;
您不再需要new LinkEventHandler(...)
- 从C#2开始,可以使用方法组转换,您可以使用它来转换方法组(方法名称) )代表类型。
frmEventGenerate.Evt += ReceiveEvent;
...而且根本不需要frmGen
变量。
但是,我强烈反对你这一点 - 为什么你希望事件首先是静态的? (我还敦促你更明智地命名你的类型 - 比如“EventGenerator”在这里会更好。例如,忽略类型名称应该是Pascal案例的约定会导致令人困惑的代码。)
答案 1 :(得分:0)
//Receiver
using System;
using System.Windows.Forms;
namespace eTest
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
public void ReceiveEvent(int i)
{
MessageBox.Show("Event Received from Form: " + i.ToString());
}
private void btnNew_Click(object sender, EventArgs e)
{
int num = 0;
int x = 0;
num = Convert.ToInt32(txtForms.Text);
for (x = 0; x < num; x++)
{
frmDL f = new frmDL();
f.Evt += ReceiveEvent;
f.iID = x;
f.Text = x.ToString();
f.Show();
f.Activate();
Application.DoEvents();
}
}
}
}
//Sender
using System;
using System.Windows.Forms;
namespace eTest
{
public delegate void myEventHandler(int i);
public partial class frmDL : Form
{
public event myEventHandler Evt;
public int iID = 0;
public frmDL()
{
InitializeComponent();
}
public void SendEvent()
{
if (Evt != null)
{
Evt(this.iID);
}
}
private void btnEvent_Click(object sender, EventArgs e)
{
SendEvent();
}
}
}