Search code examples
c#winformsinvoke

Generalize Invoke function and delegate


How can I factor those two function/delegate into one general function and delegate ? Is there an easy way to do this ?

public TabControl tab;
public Label devlog;

delegate void tabHandlerCallback(bool e);
public void tabHandler(bool e)
{
    if (tab.InvokeRequired)
    {
        tab.Invoke(new tabHandlerCallback(tabHandler), new object[] { e });
    }
    else
    {
        tab.Enabled = e;
    }
}

delegate void devHandlerCallback(string e);
public void devHandler(string e)
{
    if (devlog.InvokeRequired)
    {
        devlog.Invoke(new devHandlerCallback(devHandler), new object[] { e });
    }
    else
    {
        devlog.Text = e;
    }
}
        

Solution

  • Here is how I did it :

    delegate void controlHandlerCallback(object control, object param, string field = "Text");
    public void controlHandler(object control, object param, string field="Text")
    {
        if (((Control)control).InvokeRequired)
        {
            ((Control)control).Invoke(new controlHandlerCallback(controlHandler), new object[] { control, param,field });
        }
        else
        {
            PropertyInfo propertyInfo = control.GetType().GetProperty(field);
            propertyInfo?.SetValue(control, param);
        } 
    }