using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Common
{
    /// <summary>
    /// 控件委托帮助类
    /// </summary>
    public class ThreadControlHelper
    {
        /// <summary>
        /// 跨线程设置控件属性值委托类型定义
        /// </summary>
        delegate void SetControlPropertyCallBack(Control control, string name, object value);
        /// <summary>
        /// 跨线程设置控件属性值
        /// </summary>
        public static void SetControlProperty(Control control, string name, object value)
        {
            if (control.InvokeRequired == true)
            {
                SetControlPropertyCallBack CallBack = new SetControlPropertyCallBack(SetControlProperty);
                control.Invoke(CallBack, new object[] { control, name, value });
            }
            else
            {
                Type type = control.GetType();
                type.InvokeMember(name,
                    BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance,
                  null, control, new object[] { value });
            }
        }

        /// <summary>
        /// 跨线程设置控件属性值委托类型定义
        /// </summary>
        delegate object GetControlPropertyCallBack(Control control, string name);
        /// <summary>
        /// 跨线程读取控件属性值
        /// </summary>
        public static object GetControlProperty(Control control, string name)
        {
            if (control.InvokeRequired == true)
            {
                GetControlPropertyCallBack CallBack = new GetControlPropertyCallBack(GetControlProperty);
                return control.Invoke(CallBack, new object[] { control, name });
            }
            else
            {
                Type type = control.GetType();
                return type.InvokeMember(name,
                    BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance,
                  null, control, null);
            }
        }
    }
}
