Reputation: 14122
I have a winform application that goes with name myForm
. Within this form I open another form:
private OtherForm otherForm; //this is a field
private OpenOtherForm()
{
if (otherForm == null)
{
otherForm = new OtherForm();
otherForm.FormClosing += delegate { MessageBox.Show("OtherForm will be closed"); otherForm = null};
}
MessageBox.Show("Form is already active!");
}
This works fine. But I have some methods in the second form as well. I would like to try capturing theire call.
For example if OtherForm.DoSomething() is called within the second form, I want a message box to show thi.
I tried to assign OtherForm.DoSomething() += delegate { /* mesagebox */};
But this does not compile
Upvotes: 0
Views: 405
Reputation: 39898
otherForm.FormClosing += delegate { .. }
is compiling because FormClosing is of type Event. An event can be subscribed to and when it's fired your code will run.
You can't use this syntax on a method like DoSomething()
. A method can only be called with something like otherForm.DoSomething()
. The code in DoSomething()
will then be executed.
What you can do however is create your own event and fire it when DoSomething() is executed in the second form.
Here is the MSDN Documentation on publishing your own Event.
It would be something like:
public event EventHandler RaiseCustomEvent;
public void DoSomething()
{
OnRaiseCustomEvent();
}
protected virtual void OnRaiseCustomEvent()
{
EventHandler handler = RaiseCustomEvent;
if (handler != null)
{
handler(this, EventArgs.Empty););
}
}
Upvotes: 5
Reputation: 50682
If you want to respond to a call in another form you could add an event to the other form and raise it in the method you are trying to respond to.
class Form1: Form
{
public void Button1_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.SomeMethodCalled += Form2_SomeMethodCalled;
}
public void Form2_SomeMethodCalled(object sender, EventArgs e)
{
// method in form2 called
}
}
class Form2 : Form
{
public event EventHandler SomeMethodCalled;
public void SomeMethod()
{
OnSomeMethodCalled();
// .....
}
private void OnSomeMethodCalled()
{
var s = SomeMethodCalled;
if(s != null)
{
s(this, EventArgs.Empty);
}
}
}
Upvotes: 1