using System; using System.Linq.Expressions; using System.Reflection; using System.Windows.Forms; namespace CC_Functions.Misc { public delegate void SetPropertyDelegate(TCtl control, Expression> propexpr, TProp value) where TCtl : Control; public delegate TProp GetPropertyDelegate(TCtl control, Expression> propexpr) where TCtl : Control; public delegate void InvokeActionDelegate(TCtl control, Delegate dlg, params object[] args) where TCtl : Control; public delegate TResult InvokeFuncDelegate(TCtl control, Delegate dlg, params object[] args) where TCtl : Control; public static class Forms { public static void SetProperty(this TCtl control, Expression> propexpr, TProp value) where TCtl : Control { if (control == null) throw new ArgumentNullException(nameof(control)); if (propexpr == null) throw new ArgumentNullException(nameof(propexpr)); if (control.InvokeRequired) { control.Invoke(new SetPropertyDelegate(SetProperty), control, propexpr, value); return; } var propexprm = propexpr.Body as MemberExpression; if (propexprm == null) throw new ArgumentException("Invalid member expression.", nameof(propexpr)); var prop = propexprm.Member as PropertyInfo; if (prop == null) throw new ArgumentException("Invalid property supplied.", nameof(propexpr)); prop.SetValue(control, value); } public static TProp GetProperty(this TCtl control, Expression> propexpr) where TCtl : Control { if (control == null) throw new ArgumentNullException(nameof(control)); if (propexpr == null) throw new ArgumentNullException(nameof(propexpr)); if (control.InvokeRequired) return (TProp)control.Invoke(new GetPropertyDelegate(GetProperty), control, propexpr); var propexprm = propexpr.Body as MemberExpression; if (propexprm == null) throw new ArgumentException("Invalid member expression.", nameof(propexpr)); var prop = propexprm.Member as PropertyInfo; if (prop == null) throw new ArgumentException("Invalid property supplied.", nameof(propexpr)); return (TProp)prop.GetValue(control); } public static void InvokeAction(this TCtl control, Delegate dlg, params object[] args) where TCtl : Control { if (control == null) throw new ArgumentNullException(nameof(control)); if (dlg == null) throw new ArgumentNullException(nameof(dlg)); if (control.InvokeRequired) { control.Invoke(new InvokeActionDelegate(InvokeAction), control, dlg, args); return; } dlg.DynamicInvoke(args); } public static TResult InvokeFunc(this TCtl control, Delegate dlg, params object[] args) where TCtl : Control { if (control == null) throw new ArgumentNullException(nameof(control)); if (dlg == null) throw new ArgumentNullException(nameof(dlg)); return control.InvokeRequired ? (TResult)control.Invoke(new InvokeFuncDelegate(InvokeFunc), control, dlg, args) : (TResult)dlg.DynamicInvoke(args); } } }