winform 跨线程设置或读取控件的属性

以前从来没有遇到过这个问题,跨线程访问控件,一般只有赋值的时候单独写委托什么的,但是这次却突然发现居然获取控件的值时,不写委托也会报错。

为了防止以后忘掉,咱把方法记下来。

/// <summary>
/// 控件委托帮助类
/// </summary>
public class ControlHelper
{
    /// <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);
        }
    }
}

转自CSDN的 http://download.csdn.net/detail/iscxy/663744#comment

posted @ 2013-03-26 14:53  古兰色回忆  阅读(478)  评论(0编辑  收藏  举报