Daniel
Daniel

Reputation: 1481

Subscribe to Event using a Delegate

I'm trying to subscribe to the MouseUp event for all controls on my form except for Buttons. I used a loop to subscribe all of the controls which works fine. But I want to be able to use this function on more than one form so instead of always subscribing the same function to the event, I want to pass a function as a parameter. So I created a delegate but I get this error:

Cannot implicitly convert type 'namespace.frmSettings.MouseUpDelegate' to 'System.Windows.Forms.MouseEventHandler'

Can you please tell me if what I'm trying to do is possible and if so, what am I doing wrong? Here is my code:

public frmSettings()
{
    InitializeComponent();

    //Subscribe to MouseUp events for key binds
    SubscribeMouseClicks(this, new MouseUpDelegate(frmSettings_MouseUp));
}

private delegate void MouseUpDelegate(object sender, MouseEventArgs e);
private void SubscribeMouseClicks(Control parentControl, MouseUpDelegate mouseUpDelegate)
{
    foreach (Control ctrl in parentControl.Controls)
    {
        if (ctrl.GetType() != typeof(Button))
        {
            ctrl.MouseUp += mouseUpDelegate; //This line causes the error. If I change mouseUpDelegate to frmSettings_MouseUp it works
            if (ctrl.HasChildren)
            {
                SubscribeMouseClicks(ctrl, mouseUpDelegate);
            }
        }
    }
}

I've tried searching for an answer but can't find what I'm looking for.

Any help would be greatly appreciated.

Upvotes: 1

Views: 4415

Answers (1)

Sweeper
Sweeper

Reputation: 270890

You don't need to declare a brand new delegate to do this. MouseUp event is defined using a delegate type, MouseEventHandler. This means that you just need to store an instance of MouseEventHandler.

So remove this declaration:

private delegate void MouseUpDelegate(object sender, MouseEventArgs e);

And write the method like so:

private void SubscribeMouseClicks(Control parentControl, MouseEventHandler eventHandler)
{
    foreach (Control ctrl in parentControl.Controls)
    {
        if (ctrl.GetType() != typeof(Button))
        {
            ctrl.MouseUp += eventHandler;
            if (ctrl.HasChildren)
            {
                SubscribeMouseClicks(ctrl, eventHandler);
            }
        }
    }
}

And call it like this:

SubscribeMouseClicks(this, frmSettings_MouseUp);

Upvotes: 1

Related Questions