I have the following function.
What it does is, given a Control (most likely a windows form) i want to have all of the controls contained that "obey" the Rules ( a function screening the controls i want ) subscribe to an event (lets say KeyDown).
The question is: how do i unsubscribe? Or more importantly, do i need to?
Since i will be using this one on the Load event of forms on the form itself will i really need to unsubscribe if the form closes?
(after some light reading and a little understanding of the GC i suspect i don't need to unsubscribe but I'm not sure)
//an example of using the function
private void Form1_Load(object sender, EventArgs e)
{
MyEventHandler.CreateKeyDownEventHandlers(this);
}
//the function
public static void CreateEventHandlers(Control Ctrl)
{
foreach (Control c in Ctrl.Controls)
{
//bool Rules(Control) a function that determines to what controls'
//events to apply the handler
if ( Rules(c) )
{
c.KeyDown += (s, e) =>
{
// do something
};
}
//a control might be a groupbox so we want their contained
//controls also
if (c.Controls != null)
{
if (c.Controls.Count > 0)
{
CreateEventHandlers(c);
}
}
}
}
This is my first try with events, delegates, anonymous functions and lambdas so if i did something really stupid tell me.