Can someone tell me what is wrong in my code? Try it with static and non-static event by commenting/uncommenting appropriate lines of code.
The name of project is "Try It" and this is main form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Try_It
{public delegate void dlgt_Delegate(); // This is delegate...
public partial class frm_Main : Form
{//public static event dlgt_Delegate evnt_Event; //... and this should be static event.
public event dlgt_Delegate evnt_Event; //... and this should be non-static event.
public frm_Main()
{InitializeComponent();
}
private void btn_Send_Event_Click(object sender, EventArgs e)
{if (evnt_Event != null) // If someone is subscribed...
evnt_Event(); //... tell them.
}
private void btn_Exit_Click(object sender, EventArgs e)
{this.Close();
}
}
}
This is my class which is added by Project->Add->Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Try_It
{
class cls_I_am_waiting
{
frm_Main Main = new frm_Main();
public cls_I_am_waiting() // This should be a constructor of a class,
{
//frm_Main.evnt_Event += frm_Main_evnt_Event; // I want to be notified when button is clicked on main form (static event)...
Main.evnt_Event += Main_evnt_Event; // I want to be notified when button is clicked on main form (non-static event)...
}
//void frm_Main_evnt_Event() //... with static event.
//{
// MessageBox.Show("O.K. I received it!"); //... and tell it!
//}
void Main_evnt_Event() //... with non-static event.
{
MessageBox.Show("O.K. I received it!"); //... and tell it!
}
}
}
Thanks.
VulpesPosted Jul 22, 2014, 7:28 PM
PecaPosted Jul 23, 2014, 2:34 AM
PecaPosted Jul 22, 2014, 3:18 PM
It works.
Can you explain to us this line of code:
new cls_I_am_waiting(this);
Also, I delete from code marked lines an everything works fine:
{
---> frm_Main Main = null; <--- deleted...
...and change from (frm_main main) to (frm_main Main)...
public cls_I_am_waiting(frm_main Main) // This should be a constructor of a class,
{
---> Main = main; <---- ... deleted
//frm_Main.evnt_Event += frm_Main_evnt_Event; // I want to be notified when button is clicked on main form (static event)...
Main.evnt_Event()...
VulpesPosted Jul 22, 2014, 7:30 AM